用栈。遇到数字压栈。遇到运算符则弹出前两个操作数计算结果并压栈。最后字符串矢量都处理完了就得到结果。
-
class Solution {
-
public:
-
int evalRPN(vector<string> &tokens) {
-
// IMPORTANT: Please reset any member data you declared, as
-
// the same Solution instance will be reused for each test case.
-
stack<int> st;
-
for(int i=0;i<tokens.size();i++)
-
{
-
if("+"==tokens[i]||"-"==tokens[i]||"*"==tokens[i]||"/"==tokens[i])
-
{
-
int n1=st.top(); st.pop();
-
int n2=st.top(); st.pop();
-
if("+"==tokens[i]) st.push(n1+n2);
-
if("-"==tokens[i]) st.push(n2-n1);
-
if("*"==tokens[i]) st.push(n1*n2);
-
if("/"==tokens[i]) st.push(n2/n1);
-
continue;
-
}
-
int num=0;
-
int minus=false;
-
for(int j=0;j<tokens[i].length();j++)
-
{
-
if('-'==tokens[i][j]) {minus=true; continue;}
-
num=10*num+tokens[i][j]-'0';
-
}
-
if(minus) num=0-num;
-
st.push(num);
-
}
-
return st.top();
-
}
-
};
阅读(581) | 评论(0) | 转发(0) |