LeetCode 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

 

 

Show Tags
Show Similar Problems
 
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        int len = tokens.size();
        if (len < 1) return 0;
        
        vector<int> stack;
        for (int i=0; i<len; i++) {
            string &p = tokens[i];
            if (p[0] >= '0' && p[0] <= '9' || p[0] == '-' && p.size() > 1) {
                stack.push_back(stoi(p));
            } else {
                int slen = stack.size();
                stack[slen - 2] = op(p[0], stack[slen - 2], stack[slen - 1]);
                stack.pop_back();
            }
        }

        return stack[0];
    }
    
    int op(const char op, int a, int b) {
        int res = 0;
        switch(op) {
            case '+': res = a + b; break;
            case '-': res = a - b; break;
            case '/': res = a / b; break;
            case '*': res = a * b; break;
        }
        return res;
    }
    
    int stoi(string &s) {
        int len = s.size();
        if (len < 1) return 0;
        bool neg = s[0] == '-';
        int i = neg ? 1 : 0;
        int res = 0;
        while (i < len) {
            res = res * 10 + s[i] - '0';
            i++;
        }
        return neg ? -res : res;
    }
};

数据结构栈基础,一次过

时隔一年智商又下降了:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> nums;
        for (string& token : tokens) {
            if (!isop(token)) {
                int d = 0;
                sscanf(token.c_str(), "%d", &d);
                nums.push(d);
            } else {
                int b = nums.top();
                nums.pop();
                int a = nums.top();
                nums.pop();
                nums.push(calc(a, b, token[0]));
            }
        }
        return nums.top();
    }
    bool isop(string& str) {
        return str.size() == 1 && (str[0] == '+' || str[0] == '-' || str[0] == '*' || str[0] == '/');
    }
    
    int calc(int a, int b, char op) {
        switch (op) {
            case '+': return a + b; break;
            case '-': return a - b; break;
            case '/': return a / b; break;
            case '*': return a * b; break;
        }
        return 0;
    }
};

 

posted @ 2014-07-22 10:56  卖程序的小歪  阅读(137)  评论(0编辑  收藏  举报