【两次过】Lincode 424. 逆波兰表达式求值

求逆波兰表达式的值。

在逆波兰表达法中,其有效的运算符号包括 +-*/ 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。

样例

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

解题思路:

    利用栈即可。

class Solution {
public:
    /**
     * @param tokens: The Reverse Polish Notation
     * @return: the value
     */
    int evalRPN(vector<string> &tokens) 
    {
        // write your code here
        stack<int> s;

        for(int i=0;i<tokens.size();i++)
        {
            if(!isOper(tokens[i]))
                s.push(stoi(tokens[i]));
            else
            {
                int a = s.top();
                s.pop();
                int b = s.top();
                s.pop();
                
                int res = calculate(b , a , tokens[i]);
                s.push(res);
            }
        }
        
        return s.top();
    }
    
    int calculate(int a , int b , string x)
    {
        char c = x[0];
        
        switch(c)
        {
            case '+': return a+b;
            case '-': return a-b;
            case '*': return a*b;
            case '/': return a/b;
        }
    }
    
    bool isOper(string s)
    {
        if(s.size() > 1)
            return false;
        else if(s[0] == '+' || s[0] == '-' || s[0] == '*' || s[0] == '/')
            return true;
        else
            return false;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/81047989