-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBaseball_682.java
More file actions
58 lines (54 loc) · 1.54 KB
/
Baseball_682.java
File metadata and controls
58 lines (54 loc) · 1.54 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.ArrayList;
import java.util.Stack;
public class Baseball_682 {
// Standard solution using stack
/*
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack();
for(String op : ops) {
if (op.equals("+")) {
int top = stack.pop();
int newtop = top + stack.peek();
stack.push(top);
stack.push(newtop);
} else if (op.equals("C")) {
stack.pop();
} else if (op.equals("D")) {
stack.push(2 * stack.peek());
} else {
stack.push(Integer.valueOf(op));
}
}
int ans = 0;
for(int score : stack) ans += score;
return ans;
}
*/
// My solution using arraylist
public int calPoints(String[] ops) {
int res = 0;
ArrayList<Integer> ls = new ArrayList<>();
for (String s : ops) {
int len = ls.size();
int score;
if (s.equals("+")) {
score = ls.get(len-1) + ls.get(len-2);
ls.add(score);
}
else if (s.equals("D")) {
score = 2 * ls.get(len-1);
ls.add(score);
}
else if (s.equals("C")) {
score = -ls.get(len-1);
ls.remove(len-1);
}
else {
score = Integer.valueOf(s);
ls.add(score);
}
res += score;
}
return res;
}
}