leetcode 日经贴,Cpp code -Basic Calculator

来源:互联网 发布:手机淘宝详情页怎么弄 编辑:程序博客网 时间:2024/06/05 21:15

Basic Calculator

class Solution {private:    char token;    int pos, num;    stack<char> ops;    stack<int> vals;    int getpriority(char op) {        int ret = 0;        switch(op) {            case '(': ret = 4; break;            case '+':             case '-': ret = 2; break;            case ')': ret = 1; break;            case 'd': ret = 0; break;            default: ret = -1; break;        }        return ret;    }    void next_token(const string &s) {        while (pos < s.length() && s[pos] == ' ') {            ++pos;        }        if (pos >= s.length()) {            token = '$';        } else if (s[pos] < '0' || s[pos] > '9') {            token = s[pos];            ++pos;        } else {            token = 'd';            num = 0;            while (pos < s.length() && s[pos] >= '0' && s[pos] <= '9') {                num = num * 10 + int(s[pos++] - '0');            }        }    }public:    int calculate(string s) {        while (!ops.empty()) {            ops.pop();        }        while (!vals.empty()) {            vals.pop();        }        pos = 0;        int ans;        while (true) {            next_token(s);            if (token == 'd') {                vals.push(num);            } else if (token == '$') {                if (!vals.empty()) {                    int a = vals.top();                    vals.pop();                    while (!ops.empty()) {                        int b = vals.top();                        vals.pop();                        char ch = ops.top();                        ops.pop();                        if (ch == '+') {                            a += b;                        } else {                            a = b - a;                        }                    }                    ans = a;                }                break;            } else {                while (!ops.empty() && getpriority(ops.top()) >= getpriority(token)) {                    char ch = ops.top();                    if ((ch == '+' || ch == '-') && !vals.empty()) {                        int a = vals.top();                        vals.pop();                        if (vals.empty()) {                            vals.push(a);                            break;                        }                        int b = vals.top();                        vals.pop();                        ops.pop();                        if (ch == '+') {                            vals.push(a + b);                        } else {                            vals.push(b - a);                        }                    } else {                        break;                    }                }                if (token == ')') {                    ops.pop();                } else {                    ops.push(token);                }            }        }        return ans;    }};


0 0
原创粉丝点击