-
Notifications
You must be signed in to change notification settings - Fork 277
/
BaseballGame.java
130 lines (117 loc) · 3.03 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// TC : O(n)
// SC : O(n)
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
int res = 0;
for (String s : ops) {
if (s.equals("+")) {
int top = stack.pop();
int newValue = top + stack.peek();
stack.push(top);
stack.push(newValue);
res += newValue;
}
else if (s.equals("D")) {
int newValue = stack.peek() * 2;
stack.push(newValue);
res += newValue;a
}
else if (s.equals("C")) {
int newValue = stack.pop();
res -= newValue;
}
else {
int newValue = Integer.parseInt(s);
stack.push(newValue);
res += newValue;
}
}
return res;
}
}
=======
// Author: Shobhit Behl (LC: shobhitbruh)
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> st=new Stack<>();
for(int i=0;i<ops.length;i++){
if(ops[i].equals("+")){
int a=st.pop();
int b=st.pop();
st.push(b);
st.push(a);
st.push(a+b);
}else if(ops[i].equals("C")){
st.pop();
}else if(ops[i].equals("D")){
int d=st.pop();
st.push(d);
st.push(2*d);
}else{
st.push(Integer.parseInt(ops[i]));
}
}
int sum=0;
while(st.size()>0){
int j=st.pop();
sum+=j;
}
return sum;
}
class Solution {
// TC : O(n)
// SC : O(n)
public int calPoints(String[] ops) {
Integer topEl = null;
Integer secondtopEl= null;
Stack<Integer> st = new Stack<Integer>();
for(String op : ops){
switch(op.toCharArray()[0]){
case 'C' : st.pop();
break;
case 'D' : topEl = st.peek();
st.push(2*topEl);
break;
case '+' : topEl = st.pop();
secondtopEl = st.peek();
st.push(topEl);
st.push(topEl+secondtopEl);
break;
default: st.push(Integer.parseInt(op));
break;
}
}
int ans = 0;
while(!st.isEmpty()){
ans = ans + st.pop();
}
return ans;
}
}
// TC : O(n)
// SC : O(n)
// Problem : https://leetcode.com/problems/baseball-game/
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> st = new Stack<>();
for(String c : ops) {
if(c.equals("C")) {
st.pop();
} else if(c.equals("D")) {
st.push(st.peek() * 2);
} else if(c.equals("+")) {
int t = st.pop() + st.peek();
st.push(t - st.peek());
st.push(t);
} else {
st.push(Integer.parseInt(c));
}
}
int sum = 0;
while(!st.isEmpty()) {
sum += st.pop();
}
return sum;
}
}