Wednesday, February 12, 2014

[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
bool isNumber(string a){
        if(a.empty()) return false;
        int i = 0;
        if(a.length() == 1){
            return a[0] >= '0' && a[0] <= '9';
        }
        if(a[0] == '-'|| a[0] == '+') ++i;
        for(; i<a.length(); ++i){
            if(a[i]<'0' || a[i] >'9') return false;
        }
        return true;
    }
    int str2num(string a){
        if(a.empty()) return 0;
        int ret = 0;
        bool neg = false;
        int i = 0;
        if(a[0] == '-') {
            neg = true;
            ++i;
        }
        else if(a[0] == '+') {
            neg = false;
            ++i;
        }
        for(; i < a.length(); ++i){
            ret = ret*10+(a[i]-'0');
        }
        if(neg) return -ret;
        return ret;
    }
    int evalRPN(vector<string> &tokens) {
        if(tokens.empty()) return 0;
        stack<string> s1;
        stack<int> s2;
        for(int i = tokens.size() - 1; i >= 0; --i)
            s1.push(tokens[i]);
        while(!s1.empty()){
            string cur = s1.top();
            s1.pop();
            if(isNumber(cur)){
                int curnum = str2num(cur);
                s2.push(curnum);
            }
            else{
                int b = s2.top();
                s2.pop();
                int a = s2.top();
                s2.pop();
                int res;
                switch(cur[0]){
                    case('+'): res = a+b; break;
                    case('-'): res = a-b; break;
                    case('*'): res = a*b; break;
                    case('/'): res = a/b; break;
                    default: break;
                }
                s2.push(res);
            }
        }
        return s2.top();
    }

No comments:

Post a Comment