Evaluate the value of an arithmetic expression inReverse 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
注意细节,很容易过。 3星级的题目吧。
1 要push入结果
2 两个数的计算顺序不能错,否则答案错误
class Solution {
public:
int evalRPN(vector<string> &tokens)
{
if (tokens.size() < 1) return 0;
stack<int> stk;
for (int i = 0; i < tokens.size(); i++)
{
if (!isOperand(tokens[i])) stk.push(stoi(tokens[i]));
else
{
int b = stk.top();
stk.pop();
int a = stk.top();
stk.pop();
int result = evaluate(a, b, tokens[i]);
stk.push(result);
}
}
return stk.top();
}
bool isOperand(const string &s) const
{
if (s == "+" || s == "-" || s == "*" || s == "/") return true;
return false;
}
int evaluate(int a, int b, string &op)
{
if (op == "+") return a+b;
if (op == "-") return a-b;
if (op == "*") return a*b;
return a/b;
}
};
//2014-2-19 update
int evalRPN(vector<string> &tokens)
{
stack<int> stk;
for (int i = 0; i < tokens.size(); i++)
{
if (isOperand(tokens[i]))
{
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
int t = evaluate(tokens[i], a, b);//a b 顺序不能搞错!且需要push入结果
stk.push(t);
}
else stk.push(stoi(tokens[i]));
}
return stk.top();
}
bool isOperand(string &c)
{
return c == "+" || c == "-" || c == "*" || c == "/";
}
int evaluate(string &op, int a, int b)
{
if (op == "+") return a+b;
if (op == "-") return a-b;
if (op == "*") return a*b;
return a/b;
}
本文深入探讨了逆波兰表达式的求值过程,通过使用栈数据结构来实现算术表达式的计算。重点讲解了如何通过遍历输入的字符串列表,识别操作符与操作数,并进行相应的计算,最终返回表达式的值。代码示例清晰展示了核心算法逻辑,适合编程爱好者和初学者学习。
156

被折叠的 条评论
为什么被折叠?



