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

LeetCode---(150)Evaluate Reverse Polish Notation

2015-06-23 22:49 706 查看
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:
bool isOperator(const string &op)
{
string s="+-*/";
if(op.size()==1&&s.find(op)!=string::npos)
return true;
else
return false;
}
int str2int(string s)
{
int result=0;
int base=1;
for(int i=s.size()-1;i>=0;i--)
{
if(s[i]=='-'&&i==0)
result*=-1;
else if(s[i]>='0'&&s[i]<='9'){
result+=base*(s[i]-'0');
base*=10;
}
}
return result;
}
int evalRPN(vector<string>& tokens) {
stack<int> s;
for(auto token:tokens)
{
if(!isOperator(token))
s.push(str2int(token));
else{
int y=s.top();
s.pop();
int x=s.top();
s.pop();
if(token[0]=='+')
x+=y;
else if(token[0]=='-')
x-=y;
else if(token[0]=='*')
x*=y;
else if(token[0]=='/')
x/=y;
s.push(x);
}
}
return s.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: