首页 > 其他 > 详细

【LeetCode】Evaluate Reverse Polish Notation

时间:2014-09-10 14:09:30      阅读:257      评论:0      收藏:0      [点我收藏+]

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

 

使用栈(Stack),如果是操作数则压栈,如果是操作符则弹出栈顶两个元素进行相应运算之后再压栈。

最后栈中剩余元素即计算结果。

 

class Solution 
{
public:
    int evalRPN(vector<string> &tokens) 
    {
        stack<int> stk;

        for(vector<string>::size_type st = 0; st < tokens.size(); st ++)
        {
            if(tokens[st] == "+")
            {
                int a = stk.top();
                stk.pop();
                int b = stk.top();
                stk.pop();

                stk.push(a+b);
            }
            else if(tokens[st] == "-")
            {
                int a = stk.top();
                stk.pop();
                int b = stk.top();
                stk.pop();

                stk.push(b-a);
            }
            else if(tokens[st] == "*")
            {
                int a = stk.top();
                stk.pop();
                int b = stk.top();
                stk.pop();

                stk.push(a*b);
            }
            else if(tokens[st] == "/")
            {
                int a = stk.top();
                stk.pop();
                int b = stk.top();
                stk.pop();

                stk.push(b/a);
            }
            else
            {
                stk.push(atoi(tokens[st].c_str()));
            }
        }
        return stk.top();
    }
};

bubuko.com,布布扣

 

【LeetCode】Evaluate Reverse Polish Notation

原文:http://www.cnblogs.com/ganganloveu/p/3964274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!