-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseballGame.java
More file actions
43 lines (34 loc) · 1.1 KB
/
Copy pathBaseballGame.java
File metadata and controls
43 lines (34 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package LeetcodePractice;
import java.util.*;
public class BaseballGame {
public static void main(String[] args) {
String[] ops1 = {"5","2","C","D","+"};
System.out.println(calPoints(ops1));
String[] ops2 = {"5","-2","4","C","D","9","+","+"};
System.out.println(calPoints(ops2));
String[] ops3 = {"1","C"};
System.out.println(calPoints(ops3));
}
public static int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
for (String op : ops) {
if (op.equals("C")) {
stack.pop();
} else if (op.equals("D")) {
stack.push(stack.peek() * 2);
} else if (op.equals("+")) {
int top = stack.pop();
int newTop = top + stack.peek();
stack.push(top); // push back original top
stack.push(newTop);
} else {
stack.push(Integer.parseInt(op));
}
}
int sum = 0;
for (int score : stack) {
sum += score;
}
return sum;
}
}