leetcode 682. 棒球比赛 (java & python3)

java:

每日一题简单题重拳出击

class Solution {
    public int calPoints(String[] ops) {
        int ans = 0;
        int idx = 0;
        int n = ops.length;
        int[] arr = new int[1005];
        if(ops == null || n == 0) return -1;
        for(int i = 0; i < n; i++, idx++){
            String ch = ops[i];
            if(ch.equals("D")){
                arr[idx] = arr[idx - 1] * 2;
            }
            else if(ch.equals("C")){
                idx -= 2;
            }
            else if(ch.equals("+")){
                arr[idx] = arr[idx - 2] + arr[idx - 1];
            }else{
                arr[idx] = Integer.parseInt(ch);
            }
        }
        for(int i = 0; i < idx; i++){
            ans += arr[i];
        }
        return ans;
    }
}

python3:

class Solution:
    def calPoints(self, ops: List[str]) -> int:
        stack = []
        for op in ops:
            if op == "+":
                stack.append(int(stack[-1]) + int(stack[-2]))
            elif op == "D":
                stack.append(int(stack[-1]) * 2)
            elif op == "C":
                stack.pop()
            else:
                stack.append(int(op))
        return sum(stack)

你可能感兴趣的:(学习做题leetcode,leetcode,java,python,模拟,栈)