题目:
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> sta; for ( size_t i = 0; i < tokens.size(); ++i ) { if ( tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/" ) { int right = sta.top(); sta.pop(); int left = sta.top(); sta.pop(); if ( tokens[i]=="+" ) { sta.push(left+right); continue; } if ( tokens[i]=="-") { sta.push(left-right); continue; } if ( tokens[i]=="*") { sta.push(left*right); continue; } if ( tokens[i]=="/") { sta.push(left/right); continue; } } else { sta.push(atoi(tokens[i].c_str())); } } return sta.top(); } };
tips:
堆栈求逆波兰表达式口诀:遇上数字进栈;遇上操作符先出栈两个元素,计算结果后再压入栈。
======================================================
第二次过这道题,思路记得比较清楚。这里需要记住一个函数c++ atoi (string 转 int),这样在读入的时候转一次就够了。
stack里面存的是数字。操作符不进栈。
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> sta; for ( int i=0; i<tokens.size(); ++i ) { if ( tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/" ) { int right = sta.top(); sta.pop(); int left = sta.top(); sta.pop(); if ( tokens[i]=="+" ) { sta.push(right+left); } else if ( tokens[i]=="-") { sta.push(left - right); } else if ( tokens[i]=="*" ) { sta.push(right * left); } else { sta.push(left / right); } } else { sta.push(atoi(tokens[i].c_str())); } } return sta.top(); } };