TreeviewCopyright © aleen42 all right reserved, powered by aleen42
682. 棒球比赛
https://leetcode-cn.com/problems/baseball-game/
Java
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
int top = 0, temp = 0, sum = 0;
for(String str : ops) {
if(str.equals("C")) {
sum -= stack.pop();
}else if(str.equals("D")) {
sum += stack.push(2 * stack.peek());
}else if(str.equals("+")) {
top = stack.pop();
temp = top + stack.peek();
stack.push(top);
sum += stack.push(temp);
}else {
stack.push(Integer.parseInt(str));
sum += Integer.parseInt(str);
}
}
return sum;
}
}
Python
'''
Author: Goog Tech
Date: 2020-08-31 17:36:50
LastEditTime: 2020-08-31 17:37:13
Description: https://leetcode-cn.com/problems/baseball-game/
FilePath: \leetcode-googtech\#682. Baseball Game\Solution.py
WebSite: https://algorithm.show/
'''
class Solution(object):
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
stack = []
for op in ops:
if op == '+':
stack.append(stack[-1] + stack[-2])
elif op == 'C':
stack.pop()
elif op == 'D':
stack.append(2 * stack[-1])
else:
stack.append(int(op))
return sum(stack)