文章目录

LeetCode地址:https://leetcode.com/problems/evaluate-reverse-polish-notation/

Problem:
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> numStack=new Stack<Integer>();
Integer ret=Integer.MAX_VALUE;
for(String str:tokens)
{
if(str.matches("-?\\d+"))
{
numStack.push(Integer.parseInt(str));


}else{

ret=numStack.pop();
switch(str)
{
case "+":ret=numStack.pop()+ret;break;
case "-":ret=numStack.pop()-ret;break;
case "*":ret=numStack.pop()*ret;break;
case "/":ret=numStack.pop()/ret;break;
}
numStack.push(ret);

}
}


return numStack.pop();
}
}

本作品采用[知识共享署名-非商业性使用-相同方式共享 2.5]中国大陆许可协议进行许可,我的博客欢迎复制共享,但在同时,希望保留我的署名权kubiCode,并且,不得用于商业用途。如您有任何疑问或者授权方面的协商,请给我留言

文章目录