LeetCode problem#682
Baseball Game
Solved in 1 languageJava
Solution
35 lines
1import java.util.Stack;
2
3class Solution {
4 public int calPoints(String[] operations) {
5 Stack<String> stack = new Stack<String>();
6
7 for (int i = 0; i < operations.length; i++) {
8 if (operations[i].equals("D")) {
9 int peeked = Integer.parseInt(stack.peek());
10 stack.push(Integer.toString(peeked * 2));
11 }
12 else if (operations[i].equals("C")) {
13 stack.pop();
14 }
15 else if (operations[i].equals("+")) {
16 String popped = stack.pop();
17 int operand1 = Integer.parseInt(popped);
18 int operand2 = Integer.parseInt(stack.peek());
19 stack.push(popped);
20 stack.push(Integer.toString(operand1 + operand2));
21 }
22 else {
23 // an integer
24 stack.push(operations[i]);
25 }
26 }
27
28 int sum = 0;
29 while (!stack.isEmpty()) {
30 sum += Integer.parseInt(stack.pop());
31 }
32
33 return sum;
34 }
35}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.