Skip to content

Commit d247fe6

Browse files
committed
add prob #1190; O(N^2) in time and O(N) in space;
1 parent 90daa3a commit d247fe6

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
You are given a string s that consists of lower case English letters and brackets. 
3+
4+
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
5+
6+
Your result should not contain any brackets.
7+
8+
 
9+
10+
Example 1:
11+
12+
Input: s = "(abcd)"
13+
Output: "dcba"
14+
Example 2:
15+
16+
Input: s = "(u(love)i)"
17+
Output: "iloveu"
18+
Explanation: The substring "love" is reversed first, then the whole string is reversed.
19+
Example 3:
20+
21+
Input: s = "(ed(et(oc))el)"
22+
Output: "leetcode"
23+
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
24+
Example 4:
25+
26+
Input: s = "a(bcdefghijkl(mno)p)q"
27+
Output: "apmnolkjihgfedcbq"
28+
 
29+
30+
Constraints:
31+
32+
0 <= s.length <= 2000
33+
s only contains lower case English characters and parentheses.
34+
It's guaranteed that all parentheses are balanced.
35+
36+
来源:力扣(LeetCode)
37+
链接:https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses
38+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
39+
*/
40+
41+
/* O(N^2) in time and O(N) in space */
42+
#include <string>
43+
#include <stack>
44+
#include <queue>
45+
using namespace std;
46+
47+
class Solution {
48+
public:
49+
string reverseParentheses(string s) {
50+
stack<char> a;
51+
string res;
52+
53+
for(int i=0; i<(int)s.size(); ++i){
54+
if(s[i]=='('){
55+
a.push(s[i]);
56+
}
57+
else if(s[i]==')'){
58+
queue<char> b;
59+
while(a.top()!='('){
60+
b.push(a.top());
61+
a.pop();
62+
}
63+
a.pop(); // remove '('
64+
65+
while(!b.empty()){
66+
a.push(b.front());
67+
b.pop();
68+
}
69+
}
70+
else{
71+
a.push(s[i]);
72+
}
73+
}
74+
75+
stack<char> b;
76+
while(!a.empty()){
77+
b.push(a.top());
78+
a.pop();
79+
}
80+
while(!b.empty()){
81+
res.push_back(b.top());
82+
b.pop();
83+
}
84+
85+
return res;
86+
}
87+
};

0 commit comments

Comments
 (0)