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

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

2017-09-14 17:01 399 查看

题目链接:

https://leetcode.com/problems/evaluate-reverse-polish-notation/description/

描述

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

输入

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

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

输出

样例输入

样例输出

算法思想:

方法一:用栈来处理,从左向右依次扫描,如果遇到数字压栈,如果遇到加减乘除,从栈中弹出2个数字,进行运算,结果压入栈,直至扫描完成,栈里的最后结过就是运算结果

方法二:利用递归原理,

方法三:从左向右扫描,并压栈,用2个数保存每次扫描的最后2个数,当遇到加减乘除的时候,用这两个数运算后压栈,最后的就是最后结果

源代码

//方法一
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<string> str;

int a, b;
//      int result;
for (int i = 0; i < tokens.size(); i++)
{
if (tokens[i].size() == 1 && ("0">tokens[i] || "9"<tokens[i])) //if is +-*/
{
char ch = tokens[i].c_str()[0];
a = stoi(str.top()); str.pop();
b = stoi(str.top()); str.pop();
switch (ch)
{
case '+':
a = a + b;
break;
case '-':
a = b - a;
break;
case '*':
a = a * b;
break;
case <
4000
span class="hljs-string">'/':
a = b / a;
break;
default:
break;
}
stringstream ss;
ss << a;
str.push(ss.str());
}
else                  //when it is number
{
str.push((tokens[i]));
}
}
return stoi(str.top());
}
};

//方法二

class Solution{
public:
int evalRPN(vector<string> &tokens) {
string s = tokens.back(); tokens.pop_back();
if ( s== "*" || s=="/" || s=="+" || s == "-" ){
int r2 = evalRPN(tokens);
int r1 = evalRPN(tokens);
if ( s=="*") return r1*r2;
if ( s=="/") return r1/r2;
if ( s=="+") return r1+r2;
if ( s=="-") return r1-r2;
}
else
return atoi(s.c_str());
}
};
//方法三
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
int s1,s2;
s1=s2=0;
int res=0;
for(vector<string>::iterator iter=tokens.begin();iter!=tokens.end();iter++)
{
if (*iter == "+")
{
s1=st.top();
st.pop();
s2=st.top();
st.pop();
res=s1+s2;
st.push(res);
}

else if (*iter == "-")
{
s1=st.top();
st.pop();
s2=st.top();
st.pop();
res=s2-s1;
st.push(res);
}
else if (*iter == "*")
{
s1=st.top();
st.pop();
s2=st.top();
st.pop();
res=s1*s2;
st.push(res);
}
else if (*iter== "/")
{
s1=st.top();
st.pop();
s2=st.top();
st.pop();
res=s2/s1;
st.push(res);
}
else
{
st.push(atoi((*iter).c_str()));
}
}
return st.top();

}

};


最优源代码



算法复杂度:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐