Question:
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
Solution:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int len = tokens.size();
int stack[5000];
int top = -1;
int t1 = 0;
int t2 = 0;
for(int i = 0 ; i < len ; i++){
if(top >= 1){
t1 = stack[top];
t2 = stack[top-1];
}
switch(tokens[i][0]){
case '+':stack[--top] = t1+t2;break;
case '*':stack[--top] = t2*t1;break;
case '/':stack[--top] = t2/t1;break;
case '-':if(tokens[i].size()==1){
stack[--top] = t2-t1; break;
}
default: stack[++top] = atoi(tokens[i].c_str());
//stringstream ss;
// ss<<tokens[i];
// ss>>stack[++top];
}
}
return stack[0];
}
};
总结:
1、后缀表达式求值,典型的栈应用。相应的还有中缀表达式转换后缀表达式
:使用两个栈,一个存储运算符号,一个存储数字,运算符栈一直要保证栈顶运算符号优先级最大。
2、stringstream最是耗时beat 8%,16ms
改用atoi beat 72%,9ms。效率相差一倍
本文介绍了一种解决逆波兰表达式求值问题的方法,并通过一个C++类实现。该方法利用栈来处理算术运算,包括加减乘除等基本操作。文中还对比了使用stringstream和atoi进行字符串转整数的性能差异。
211

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



