问题:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路:
用栈解决:遇到数字入栈,如到操作符将栈的前两个数字出栈并且进行运算,再将结果入栈即可;最后返回的是栈内的最后一个数字,将其出栈即可。
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
Set<String> dot = new HashSet<String>();
dot.add("+");
dot.add("-");
dot.add("*");
dot.add("/");
for(int i=0;i<tokens.length;i++){
if(!dot.contains(tokens[i])){
System.out.println("--------"+tokens[i]);
s.push(Integer.parseInt(tokens[i]));
}else{
int num1 = s.pop();
int num2 = s.pop();
if(tokens[i].equals("+")){
s.push(num1+num2);
}else if(tokens[i].equals("-")){
s.push(num2-num1);
}else if(tokens[i].equals("*")){
s.push(num1*num2);
}else if(tokens[i].equals("/")){
s.push(num2/num1);
}
}
}
return s.pop();
}