每日一题-LeetCode682-棒球比赛-栈-模拟

原题链接
在这里插入图片描述

Note:

用个栈来硬模拟就好了,不过还是用vector模拟会更方便一些

代码如下:

class Solution {
public:
    int calPoints(vector<string>& ops) {
        if(ops.empty()) return 0;
        stack<int> stk;
        for(int i = 0; i < ops.size(); i ++){
            if(ops[i] == "+"){
                int x1 = stk.top();
                stk.pop();
                int x2 = stk.top();
                stk.push(x1);
                stk.push(x1 + x2);
            }
            else if(ops[i] == "D")
                stk.push(stk.top() * 2);
            else if(ops[i] == "C")
                stk.pop();
            else
                stk.push(stoi(ops[i]));
        }

        int res = 0;
        while(stk.size()){
            res += stk.top();
            stk.pop();
        }
        return res;
    }
};

版权声明:本文为Mr_Ghost812原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。