forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse-substrings-between-each-pair-of-parentheses.cpp
49 lines (47 loc) · 1.23 KB
/
reverse-substrings-between-each-pair-of-parentheses.cpp
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
// Time: O(n)
// Space: O(n)
class Solution {
public:
string reverseParentheses(string s) {
vector<int> stk;
unordered_map<int, int> lookup;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '(') {
stk.emplace_back(i);
} else if (s[i] == ')') {
int j = stk.back(); stk.pop_back();
lookup[i] = j, lookup[j] = i;
}
}
string result;
for (int i = 0, d = 1; i < s.length(); i += d) {
if (lookup.count(i)) {
i = lookup[i];
d *= -1;
} else {
result.push_back(s[i]);
}
}
return result;
}
};
// Time: O(n^2)
// Space: O(n)
class Solution2 {
public:
string reverseParentheses(string s) {
vector<string> stk = {""};
for (const auto& c : s) {
if (c == '(') {
stk.emplace_back();
} else if (c == ')') {
auto end = move(stk.back()); stk.pop_back();
reverse(end.begin(), end.end());
stk.back() += end;
} else {
stk.back().push_back(c);
}
}
return stk[0];
}
};