LeetCode_682-Baseball Game

给定一个字符串列表,字符串包含整数,’+’,’D’,’C’,整数代表一个分数,’+’代表后两个有效分数的和,’D’代表后一个有效分数的两倍,’C’代表删除后一个有效的分数值,最后求所有有效分数的和。
例子:
输入[“5”,”2”,”C”,”D”,”+”],输出30。2为无效的数,’D’是5*2,’+’是5*2+5,5+0+10+(10+5)= 30

class Solution {
public:
    int calPoints(vector<string>& ops) {
        stack<int> stackRes;
        for(int i=0; i<ops.size(); i++) {
            if(ops[i][0] == 'C') {
                if(!stackRes.empty()) {
                    stackRes.pop();
                }
            }
            else if(ops[i][0] == 'D') {
                if(!stackRes.empty()) {
                    int nNum = stackRes.top();
                    nNum *= 2;
                    stackRes.push(nNum);
                }
            }
            else if(ops[i][0] == '+') {
                if(!stackRes.empty()) {
                    int nNum = stackRes.top();
                    stackRes.pop();
                    int nSum = nNum + stackRes.top();
                    stackRes.push(nNum);
                    stackRes.push(nSum);
                }
            }
            else {
                stackRes.push(atoi(ops[i].c_str()));
            }
        }
        int nResRum = 0;
        while(!stackRes.empty()) {
            nResRum += stackRes.top();
            stackRes.pop();
        }
        return nResRum;
    }
};

可关注公众号了解更多的面试技巧

猜你喜欢

转载自www.cnblogs.com/yew0/p/11613927.html