力扣刷题:19-棒球比赛(682)

241 阅读1分钟

这道题只要使用一个栈,如果是分数,则入栈,如果是记分法则,则将分数出栈并参与运算,最后将栈中的所有分数想加即可得到最后的分数。

下面是C++实现的代码:

class Solution {
public:
    int calPoints(vector<string>& ops) {
        stack<int> s;
        for (auto op : ops) {
            if (op == "+") {
                int t = s.top();
                s.pop();
                int n = t + s.top();
                s.push(t);
                s.push(n);
            } else if (op == "D") {
                s.push(s.top() * 2);
            } else if (op == "C") {
                s.pop();
            } else {
                int n = 0;
                for (auto i : op) {
                    if (i == '-') {
                        continue;
                    }
                    n = n * 10 + (i - '0');
                }
                if (op[0] == '-') {
                    n = -n;
                }
                s.push(n);
            }
        }
        int ret = 0;
        while (!s.empty()) {
            ret += s.top();
            s.pop();
        }
        return ret;
    }
};