-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseball game.java
More file actions
64 lines (59 loc) · 1.85 KB
/
Baseball game.java
File metadata and controls
64 lines (59 loc) · 1.85 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
59
60
61
62
63
//using stack
class Solution {
public int calPoints(String[] ops) {
int sum=0;
Stack<String> stack= new Stack<>();
for(String s : ops)
{
switch(s)
{
case "+" :
long last=Long.parseLong(stack.peek());
long secondLast=Long.parseLong(stack.get(stack.size()-2));
sum+=last+secondLast;
stack.push(String.valueOf(last+secondLast));
break;
case "D":
long newScore=Long.parseLong(stack.peek())*2;
sum+=newScore;
stack.push(String.valueOf(newScore));
break;
case "C":
long delete=Long.parseLong(stack.pop());
sum-=delete;
break;
default:
stack.push(s);
sum+=Long.parseLong(s);
break;
}
}
if(sum<=Integer.MAX_VALUE)
return (int) sum;
return -1;
}
}
//using linked list
class Solution {
public int calPoints(String[] ops) {
var st = new LinkedList<Integer>();
int sum = 0;
for (String op : ops) {
if (op.equals("D")) {
sum += st.peekLast() * 2;
st.addLast(st.peekLast() * 2);
} else if (op.equals("C")) {
sum -=st.removeLast();
} else if (op.equals("+")) {
int n1 = st.get(st.size()-2);
int n2 = st.get(st.size()-1);
st.addLast(n1 + n2);
sum += n1 + n2;
} else {
sum += Integer.parseInt(op);
st.addLast(Integer.parseInt(op));
}
}
return sum;
}
}