当前位置:网站首页>682. baseball game

682. baseball game

2022-06-11 08:56:00 Drag is me

leetcode Force button to brush questions and punch in

subject :682. baseball game
describe : You are now a recorder of a special baseball game . The game consists of several rounds , The score of the past few rounds may affect the score of the next few rounds .

At the beginning of the game , The record is blank . You get a list of strings that record operations ops, among ops[i] It's the number one you need to record i Actions ,ops Follow these rules :

Integers x - This is a new round x
“+” - The new score of this round is the sum of the previous two scores . Topic data ensures that there are always two valid scores in front of this operation .
“D” - The new score in this round is twice that of the previous one . The title data ensures that there is always a valid score before recording this operation .
“C” - The previous score is invalid , Remove it from the record . The title data ensures that there is always a valid score before recording this operation .
Please return the sum of all the scores in the record .

Their thinking

1、 In and out operations must be stack ;
2、+ When , In order to get the first two scores , You need to pop up the previous score first , After getting the second score before , Put back the previous score ;
3、stoi function ( String to integer ) It's also very easy to use ;

Source code ##

class Solution {
    
public:
    int calPoints(vector<string>& ops) {
    
        stack<int>s;
        int ans = 0;
        for (int i = 0; i < ops.size(); ++i) {
    
            char ch = ops[i][0];
            if (ch == 'C') {
     
                ans -= s.top();
                s.pop();
            } else if (ch == 'D') {
    
                int temp = s.top() * 2;
                s.push(temp);
                ans += s.top();
            } else if (ch == '+'){
    
                int pre1 = s.top();
                s.pop();
                int pre2 = s.top();
                s.push(pre1);
                int temp = pre1 + pre2;
                s.push(temp);
                ans += s.top();
            } else {
    
                int temp = stoi(ops[i]);
                s.push(temp);
                ans += temp;
            }
        }
        return ans;
    }
};
原网站

版权声明
本文为[Drag is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110855010686.html