-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathBaseballGame.java
47 lines (35 loc) · 919 Bytes
/
BaseballGame.java
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
43
44
45
46
47
package leetcode;
import java.util.Stack;
/**
* Created by nikoo28 on 12/16/17 4:30 PM
*/
class BaseballGame {
public int calPoints(String[] ops) {
Stack<Integer> scoreStack = new Stack<>();
int sum = 0;
for (String op : ops) {
if (op.equals("C")) {
int cancelledScore = scoreStack.pop();
sum -= cancelledScore;
continue;
}
if (op.equals("D")) {
int oldScore = scoreStack.peek();
sum += (oldScore * 2);
scoreStack.push(oldScore * 2);
continue;
}
if (op.equals("+")) {
int num1 = scoreStack.get(scoreStack.size() - 1);
int num2 = scoreStack.get(scoreStack.size() - 2);
int total = num1 + num2;
scoreStack.push(total);
sum += total;
continue;
}
scoreStack.push(Integer.parseInt(op));
sum += Integer.parseInt(op);
}
return sum;
}
}