您的位置:首页 > 其它

逆波兰表达式求值

2015-09-14 17:03 363 查看
题目:求逆波兰表达式的值。在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。

例子

[“2”, “1”, “+”, “3”, “*”] -> ((2 + 1) * 3) -> 9

[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

方法:逐一扫描每个token,如果是数字,则push入stack,如果是运算符,则从stack中pop出两个数字,进行运算,将结果push回stack。最后留在stack里的数即为最终结果。

class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> s;
for(int i=0; i<tokens.size(); i++) {
if(isOp(tokens[i])) {
int y = s.top();
s.pop();
int x = s.top();
s.pop();
s.push(evaluate(x, y, tokens[i]));
}
else {
s.push(stoi(tokens[i], nullptr, 10));
//s.push(atoi(tokens[i].c_str()));
}
}
return s.top();
}

bool isOp(string s) {
if(s=="+" || s=="-" || s=="*" || s=="/") return true;
return false;
}

int evaluate(int x, int y, string op) {
if(op=="+")
return x+y;
else if(op=="-")
return x-y;
else if(op=="*")
return x*y;
else if(op=="/")
return x/y;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode stack