【leetcode刷题笔记】Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
题解:典型的栈的应用——计算后缀表达式。
思路很简单:
遇到符号就从栈里面弹出来两个元素进行相应的计算后得到的结果重新放回栈中
遇到数字就直接压入栈中。
代码如下:
1 public class Solution { 2 public int evalRPN(String[] tokens) { 3 Stack<Integer> s = new Stack<Integer>(); 4 5 for(String x:tokens){ 6 if(x.equals("+")) 7 s.push(s.pop()+s.pop()); 8 else if(x.equals("-")){ 9 int b = s.pop(); 10 int a = s.pop(); 11 s.push(a-b); 12 } 13 else if(x.equals("*")) 14 s.push(s.pop()*s.pop()); 15 else if(x.equals("/")){ 16 int b = s.pop(); 17 int a = s.pop(); 18 s.push(a/b); 19 } 20 else{ 21 s.push(Integer.parseInt(x)); 22 } 23 } 24 25 return s.pop(); 26 27 } 28 }
特别注意的地方有两点:
1.将一个String转换成Integer用Integer.parseInt()函数
2.开始我用的是“==”来比较两个字符串是否相等,后来发现“==”其实比较的是字符串的地址是否相等,如果要比较字符串的内容是否相等要用s.equals()函数。
不过很奇怪的一点是在自己电脑的eclipse上面用“==”居然也能够算出正确的值。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了