您的位置:首页 > 编程语言 > Lua

LeetCode-Evaluate Reverse Polish Notation

2014-03-17 16:45 411 查看
水题一枚,直接压栈出栈即可,不过调用内置函数可以节省很多力气,如:

int stoi(const string& s);


具体代码如下:

class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> s;
for(auto token:tokens){
if(is_digit(token))
s.push(stoi(token));
else{
int a = s.top();
s.pop();
int b = s.top();
s.pop();
switch(token[0]){
case '+':
b+=a; break;
case '-':
b-=a; break;
case '*':
b*=a; break;
case '/':
b/=a; break;
}
s.push(b);
}
}
return s.top();
}

private:
static bool is_digit(const string& token){
if((token.size()>1)||(token[0]>='0'&&token[0]<='9'))
return true;
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode