标签:
很简单的stack,注意operation order
public class Solution { public int evalRPN(String[] tokens) { if(tokens ==null|| tokens.length==0) return 0; Stack<String> st = new Stack<String>(); String opr = "+-*/"; for(int i=0;i<tokens.length;i++){ if(!opr.contains(tokens[i])){ st.push(tokens[i]); }else{ cal(st,tokens[i]); } } return Integer.valueOf(st.pop()); } private void cal(Stack<String> st, String op){ int x = Integer.valueOf(st.pop()); int y = Integer.valueOf(st.pop()); switch(op){ case "+": st.push(String.valueOf(x+y)); break; case "-": st.push(String.valueOf(y-x)); break; case "*": st.push(String.valueOf(x*y)); break; case "/": st.push(String.valueOf(y/x)); break; } } }
Evaluate Reverse Polish Notation
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4576237.html