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 bracket.
Example 1:
Input: s = "(abcd)" Output: "dcba"
Example 2:
Input: s = "(u(love)i)" Output: "iloveu"
Example 3:
Input: s = "(ed(et(oc))el)" Output: "leetcode"
Example 4:
Input: s = "a(bcdefghijkl(mno)p)q" Output: "apmnolkjihgfedcbq"
Constraints:
0 <= s.length <= 2000
s
only contains lower case English characters and parentheses.- It’s guaranteed that all parentheses are balanced.
Solution: Stack
Use a stack of strings to track all the active strings.
Iterate over the input string:
1. Whenever there is a ‘(‘, push an empty string to the stack.
2. Whenever this is a ‘)’, pop the top string and append the reverse of it to the new stack top.
3. Otherwise, append the letter to the string on top the of stack.
Once done, the (only) string on the top of the stack is the answer.
Time complexity: O(n^2)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua class Solution { public: string reverseParentheses(string s) { stack<string> st; st.push(""); for (char c : s) { if (c == '(') st.push(""); else if (c != ')') st.top() += c; else { string t = st.top(); st.pop(); st.top().insert(end(st.top()), rbegin(t), rend(t)); } } return st.top(); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment