Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 210b901

Browse files
1190. Reverse Substrings Between Each Pair of Parentheses
1 parent ac351e1 commit 210b901

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Runtime: 0 ms
2+
// Memory Usage: 8.7 MB
3+
class Solution {
4+
public:
5+
string reverseParentheses(string s) {
6+
string res = "";
7+
stack<int> stk;
8+
for (int i = 0; i < s.size(); i++) {
9+
if (s[i] == '(') {
10+
stk.push(i);
11+
} else if (s[i] == ')') {
12+
int idx = stk.top();
13+
stk.pop();
14+
reverse(s.begin() + idx + 1, s.begin() + i);
15+
}
16+
}
17+
for (char a : s) {
18+
if (a != '(' && a != ')') {
19+
res += a;
20+
}
21+
}
22+
return res;
23+
}
24+
};
25+
26+
27+
class Solution {
28+
public:
29+
string reverseParentheses(string s) {
30+
string res = "";
31+
vector<int> pairs(s.size());
32+
stack<int> open;
33+
for (int i = 0; i < s.size(); i++) {
34+
if (s[i] == '(') {
35+
open.push(i);
36+
} else if (s[i] == ')') {
37+
int j = open.top();
38+
open.pop();
39+
pairs[i] = j;
40+
pairs[j] = i;
41+
}
42+
}
43+
int direction = 1;
44+
for (int i = 0; i < s.size(); i += direction) {
45+
cout << i << " ";
46+
if (s[i] == '(' || s[i] == ')') {
47+
i = pairs[i];
48+
direction = -direction;
49+
} else {
50+
res += s[i];
51+
}
52+
}
53+
return res;
54+
}
55+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /