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
import java.util.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<>();
int a,b;
int c;
for(int i =0; i<tokens.length;++i)
{
if( tokens[i].equals("+"))
{
b = s.pop();
a = s.pop();
c = a + b;
s.push(c);
}else if(tokens[i].equals("-"))
{
b = s.pop();
a = s.pop();
c = a - b;
s.push(c);
}else if(tokens[i].equals("*"))
{
b = s.pop();
a = s.pop();
c = a * b;
s.push(c);
}else if(tokens[i].equals("/"))
{
b = s.pop();
a = s.pop();
c = a/b;
s.push(c);
}else
{
s.push(Integer.parseInt(tokens[i]));
}
}
return s.pop();
}
}

本文介绍了一种解决逆波兰表达式求值问题的方法。利用栈数据结构处理加减乘除运算,支持整数和表达式作为操作数。示例包括了如何解析和计算逆波兰表达式的具体步骤。
255

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



