Skip to content

Latest commit

 

History

History
63 lines (55 loc) · 1.74 KB

682.-bang-qiu-bi-sai.md

File metadata and controls

63 lines (55 loc) · 1.74 KB

682. 棒球比赛

https://leetcode-cn.com/problems/baseball-game/

解法一:c++栈

相当naive,每轮得分存在栈中,便于题中’C‘(撤销)’D‘(加倍)和’+‘(前两轮)操作

class Solution {
public:
    int calPoints(vector<string>& ops) {
        stack<int> s;
        int sum = 0;
        for (int i = 0; i < ops.size(); i++) {//遍历ops,对每种情况处理
            if (ops[i] == "C") {
                s.pop();
            }
            else if (ops[i] == "D") {
                int tmp = s.top() * 2;
                s.push(tmp);
            }
            else if (ops[i] == "+") {
                int tmp1 = s.top();
                s.pop();
                int tmp2 = s.top() + tmp1;
                s.push(tmp1);
                s.push(tmp2);
            }
            else { // 若是数字
                int tmp = stoi(ops[i]);
                s.push(tmp);
            }
        }
        while(!s.empty()) {  //求和
            sum += s.top();
            s.pop();
        }
        return sum;
    }
};

解法二:py栈

用一个list充当栈,好处是没有c++的栈那么死板,可以随意访问,只要保持栈的特性就好。写出来才发现和官方题解一模一样,巧了。

class Solution:
    def calPoints(self, ops: List[str]) -> int:
        stack = []    #得分栈
        for op in ops:
            if op == 'C':
                stack.pop()
            elif op == 'D':
                stack.append(stack[-1] * 2)
            elif op == '+':
                stack.append(stack[-1] + stack[-2])
            else:
                stack.append(int(op))
        return sum(stack)    #每轮得分求和