class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<Integer>();
for(String token:tokens)
{
if(token.equals("+")||token.equals("-")||token.equals("*")||token.equals("/"))
{
int n2=stack.pop();
int n1=stack.pop();
if(token.equals("+"))
stack.push(n1+n2);
else if(token.equals("-"))
stack.push(n1-n2);
else if(token.equals("*"))
stack.push(n1*n2);
else
stack.push(n1/n2);
}
else
stack.push(Integer.parseInt(token));
}
return stack.isEmpty()?0:stack.pop();
}
}
本文介绍了一种使用栈数据结构求解逆波兰表示法(RPN)表达式的算法实现。通过遍历输入的字符串数组,算法能正确处理加、减、乘、除四种运算,并返回最终计算结果。
356

被折叠的 条评论
为什么被折叠?



