forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_682.java
54 lines (49 loc) · 1.82 KB
/
_682.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
48
49
50
51
52
53
54
package com.fishercoder.solutions;
import java.util.Stack;
public class _682 {
public static class Solution1 {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
int sum = 0;
int firstLast = Integer.MIN_VALUE;
int secondLast = Integer.MIN_VALUE;
for (String op : ops) {
if (op.equals("+")) {
if (!stack.isEmpty()) {
firstLast = stack.pop();
}
if (!stack.isEmpty()) {
secondLast = stack.pop();
}
int thisRoundPoints = firstLast + secondLast;
if (secondLast != Integer.MIN_VALUE) {
stack.push(secondLast);
}
if (firstLast != Integer.MIN_VALUE) {
stack.push(firstLast);
}
stack.push(thisRoundPoints);
sum += thisRoundPoints;
firstLast = Integer.MIN_VALUE;
secondLast = Integer.MIN_VALUE;
} else if (op.equals("D")) {
if (!stack.isEmpty()) {
int thisRoundPoints = stack.peek() * 2;
stack.push(thisRoundPoints);
sum += thisRoundPoints;
}
} else if (op.equals("C")) {
if (!stack.isEmpty()) {
int removedData = stack.pop();
sum -= removedData;
}
} else {
Integer val = Integer.parseInt(op);
sum += val;
stack.push(val);
}
}
return sum;
}
}
}