150. 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 int evalRPN(String[] tokens) {
 2         int a,b;
 3         Stack<Integer> S = new Stack<Integer>();
 4         for (String s : tokens) {
 5             if(s.equals("+")) {
 6                 S.add(S.pop()+S.pop());
 7             }
 8             else if(s.equals("/")) {
 9                 b = S.pop();
10                 a = S.pop();
11                 S.add(a / b);
12             }
13             else if(s.equals("*")) {
14                 S.add(S.pop() * S.pop());
15             }
16             else if(s.equals("-")) {
17                 b = S.pop();
18                 a = S.pop();
19                 S.add(a - b);
20             }
21             else {
22                 S.add(Integer.parseInt(s));
23             }
24         }
25         return S.pop();        
26     }
复制代码

 

 

 

 

 
posted @   daniel456  阅读(129)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示