LeetCode 682 棒球比赛
方法1:栈模拟
class Solution:
def calPoints(self, operations: List[str]) -> int:
nums = list(); ans = 0
for op in operations:
if op == "+":
nums.append(nums[-2] + nums[-1])
elif op == "D":
nums.append(2 * nums[-1])
elif op == "C":
ans -= nums.pop()
continue
else:
nums.append(int(op))
ans += nums[-1]
return ans
- ArrayList 删除元素 remove
class Solution {
public int calPoints(String[] operations) {
List<Integer> nums = new ArrayList<Integer>();
int n = 0, ans = 0;
for (String op : operations) {
switch (op.charAt(0)) {
case '+':
nums.add(nums.get(n - 2) + nums.get(n - 1));
break;
case 'D':
nums.add(nums.get(n - 1) * 2);
break;
case 'C':
ans -= nums.remove(n - 1);
n -= 1;
break;
default:
nums.add(Integer.parseInt(op));
break;
}
if (op.charAt(0) != 'C') {
n += 1; ans += nums.get(n - 1);
}
}
return ans;
}
}
标签:operations,07,nums,int,get,29,2024,ans,op
From: https://www.cnblogs.com/XuGui/p/18329637