Code & Func
2019-11-09

第5天。

今天的题目是:Reverse Substrings Between Each Pair of Parentheses


You are given a string s that consists of lower case English letters and brackets.

Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should not contain any brackets.

Example 1:

1
Input: s = "(abcd)"
2
Output: "dcba"

Example 2:

1
Input: s = "(u(love)i)"
2
Output: "iloveu"
3
Explanation: The substring "love" is reversed first, then the whole string is reversed.

Example 3:

1
Input: s = "(ed(et(oc))el)"
2
Output: "leetcode"
3
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.

Example 4:

1
Input: s = "a(bcdefghijkl(mno)p)q"
2
Output: "apmnolkjihgfedcbq"

Constraints:

  • 0 <= s.length <= 2000
  • s only contains lower case English characters and parentheses.
  • It’s guaranteed that all parentheses are balanced.

很简单的一道题,和昨天那道差不多的思路,都是用栈来解决嵌套问题就好了,甚至比昨天那道题还要简单,所以直接放代码了:

1
string reverseParentheses(string s) {
2
stack<string> st;
3
st.push(string());
4
for(int i = 0;i < s.size(); i++) {
5
if (s[i] == '(') {
6
st.push(string());
7
} else if (s[i] == ')') {
8
string s = st.top(); st.pop();
9
st.top() += string(s.rbegin(), s.rend());
10
} else {
11
st.top().push_back(s[i]);
12
}
13
}
14
return st.top();
15
}
上一条动态