forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathternary-expression-parser.cpp
More file actions
32 lines (28 loc) · 864 Bytes
/
ternary-expression-parser.cpp
File metadata and controls
32 lines (28 loc) · 864 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
32
// Time: O(n)
// Space: O(1)
class Solution {
public:
string parseTernary(string expression) {
if (expression.empty()) {
return "";
}
string stack;
for (int i = expression.length() - 1; i >= 0; --i) {
auto c = expression[i];
if (!stack.empty() && stack.back() == '?') {
stack.pop_back(); // pop '?'
auto first = stack.back(); stack.pop_back();
stack.pop_back(); // pop ':'
auto second = stack.back(); stack.pop_back();
if (c == 'T') {
stack.push_back(first);
} else {
stack.push_back(second);
}
} else {
stack.push_back(c);
}
}
return string(1, stack.back());
}
};