Evaluate Reverse Polish Notation
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
解题思路:
后缀表达式计算的问题,做过计算机的同学应该都知道。遇到数字,进栈;遇到操作符,将前面两个操作数出栈,计算,将结果入栈。最后的结果会在栈中。
代码如下:
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> s; int len = tokens.size(); int num1, num2; for(int i = 0; i<len; i++){ if(tokens[i]=="+"){ num1 = s.top(); s.pop(); num2 = s.top(); s.pop(); num1 = num2 + num1; s.push(num1); }else if(tokens[i] == "-"){ num1 = s.top(); s.pop(); num2 = s.top(); s.pop(); num1 = num2 - num1; s.push(num1); }else if(tokens[i] == "*"){ num1 = s.top(); s.pop(); num2 = s.top(); s.pop(); num1 = num2 * num1; s.push(num1); }else if(tokens[i] == "/"){ num1 = s.top(); s.pop(); num2 = s.top(); s.pop(); num1 = num2 / num1; s.push(num1); }else{ s.push(stringToInt(tokens[i])); } } return s.top(); } int stringToInt(const string& s){ int len = s.length(); int result = 0; int sign = 1; int i = 0; if(s[0]=='-'){ sign = -1; i=1; } while(i<len){ result = s[i] - '0' + result * 10; i++; } return sign * result; } };
[LeetCode] Evaluate Reverse Polish Notation
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45055155