-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseball Game.cpp
More file actions
31 lines (31 loc) · 911 Bytes
/
Baseball Game.cpp
File metadata and controls
31 lines (31 loc) · 911 Bytes
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
// https://leetcode.com/problems/baseball-game/
// We can see clearly that the operations given can be applied very easily on stack
// So we used stack.
// Time Complexity - O(n), Space Complexity - O(n)
class Solution {
public:
int calPoints(vector<string>& ops) {
stack<int> ans;
for (int i = 0; i < ops.size(); i++) {
if (ops[i] == "+") {
int temp = ans.top();
ans.pop();
int news = ans.top() + temp;
ans.push(temp);
ans.push(news);
}
else if (ops[i] == "C")
ans.pop();
else if (ops[i] == "D")
ans.push(ans.top() * 2);
else
ans.push(stoi(ops[i]));
}
int res = 0;
while (ans.size()) {
res += ans.top();
ans.pop();
}
return res;
}
};