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

leetcode_150 Evaluate Reverse Polish Notation

2014-03-13 15:47 411 查看
地址:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

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


思路:模拟题,考逆波兰表达式,其实就是数的后序遍历。用栈来模拟。

关于逆波兰表达式可以参考中文维基:http://zh.wikipedia.org/zh/%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E7%A4%BA%E6%B3%95

维基里逆波兰表达式求值伪代码:

while有输入符号
读入下一个符号
IF是一个操作数
入栈

ELSE IF是一个操作符
有一个先验的表格给出该操作符需要n个参数
IF堆栈中少于n个操作数
(错误) 用户没有输入足够的操作数

Else,n个操作数出栈
计算操作符。
将计算所得的值入栈

IF栈内只有一个值
这个值就是整个计算式的结果

ELSE多于一个值
(错误) 用户输入了多余的操作数

参考代码:

class Solution {
public:
int evalRPN(vector<string> &tokens) {
int a, b, val;
stack<int> st;
for(int i = 0; i < tokens.size(); ++i)
{
string str = tokens[i];
if(!str.compare("+") || !str.compare("-") || !str.compare("*") || !str.compare("/"))
{
b = st.top();
st.pop();
a = st.top();
st.pop();
switch(*(str.c_str()))
{
case '+':
val = a+b;
break;
case '-':
val = a-b;
break;
case '*':
val = a * b;
break;
case '/':
val = a / b;
break;
default:
break;
}
st.push(val);
}
else
{
int num;
stringstream ss;
ss << str;
ss >> num;
st.push(num);
}
}
return st.top();
}
};


//SECOND TRIAL, almost the sameclass Solution {public:    int evalRPN(vector<string> &tokens) {        if(tokens.empty())            return 0;        stack<int>st;        stringstream ss;        int x, y;        string str;        for(int i = 0; i<tokens.size(); ++i)        {            if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/")            {                y = st.top();                st.pop();                x = st.top();                st.pop();                if(tokens[i]=="+")                    x += y;                else if(tokens[i]=="-")                    x -= y;                else if(tokens[i]=="*")                    x *= y;                else                    x /= y;                                    st.push(x);            }            else            {                str = tokens[i];                ss << str;                ss >> x;                st.push(x);                ss.str("");                ss.clear();            }        }        return st.top();    }};
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: