leetcode-Evaluate Reverse Polish Notation-150
根据后缀表达式求值
过程:遍历后缀表达式
1.如果是运算数,入栈
2.如果是运算符,取出栈顶的两个运算数,计算,将结果入栈
最后取出栈顶元素即为结果。这里将string转换为数字用了<sstream>的istringstream,也可以用sscanf,但是参数是char str[]
1 class Solution { 2 public: 3 bool isope(string s){ 4 if(s=="+"||s=="-"||s=="*"||s=="/") return true; 5 return false; 6 } 7 int evalRPN(vector<string>& tokens) { 8 int len=tokens.size(); 9 if(len==0) return 0; 10 stack<int> s; 11 for(int i=0;i<len;i++){ 12 if(isope(tokens[i])){ 13 int a=s.top(); 14 s.pop(); 15 int b=s.top(); 16 s.pop(); 17 if(tokens[i]=="+") s.push(b+a); 18 else if(tokens[i]=="-") s.push(b-a); 19 else if(tokens[i]=="*") s.push(b*a); 20 else s.push(b/a); 21 } 22 else{ 23 istringstream st; 24 st.str(tokens[i]); 25 int a; 26 st>>a; 27 s.push(a); 28 } 29 } 30 return s.top(); 31 } 32 };