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题意:表达式求值,注意负数
解法:用一个栈来存储数字,碰到运算符就进行出栈并运算
对C++是真的不熟,vector,stack这些数据结构的方法都不知道。。。还是用回Java吧
public class Solution {
public int stoi(String str){
return Integer.valueOf(str).intValue();
}
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
int op1 = 0;
int op2 = 0;
for(int i=0; i<tokens.length; i++){
String st = tokens[i];
if(st.equals("*") || st.equals("/") || st.equals("+") || st.equals("-")){
op2 = s.pop();
op1 = s.pop();
if(st.equals("*")) s.push(op1 * op2);
else if(st.equals("/")) s.push(op1 / op2);
else if(st.equals("+")) s.push(op1 + op2);
else if(st.equals("-")) s.push(op1 - op2);
}
else{
s.push(stoi(st));
}
}
return s.pop();
}
}