LeetCode 1190. 反转每对括号间的子串 中等
题目描述
给出一个字符串 s
(仅含有小写英文字母和括号)。
请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
注意,您的结果中 不应 包含任何括号。
示例 1:
javascript
输入:s = "(abcd)"
输出:"dcba"
示例 2:
javascript
输入:s = "(u(love)i)"
输出:"iloveu"
示例 3:
javascript
输入:s = "(ed(et(oc))el)"
输出:"leetcode"
示例 4:
javascript
输入:s = "a(bcdefghijkl(mno)p)q"
输出:"apmnolkjihgfedcbq"
提示:
javascript
0 <= s.length <= 2000
s 中只有小写英文字母和括号
我们确保所有括号都是成对出现的
来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
初始化栈,栈顶元素为 " " 遇到 '('
: 向栈顶压入空字符串遇到 ')'
: 把栈顶的最后一个元素翻转 + 栈顶倒数第二个元素遇到 字符: 直接将栈顶最后一个元素与它拼上
样例栈数组操作示意:
javascript
样例:a(bcdefghijkl(mno)p)q
a ['a']
( ['a', '']
b ['a', 'b']
c ['a', 'bc']
d ['a', 'bcd']
e ['a', 'bcde']
f ['a', 'bcdef']
g ['a', 'bcdefg']
h ['a', 'bcdefgh']
i ['a', 'bcdefghi']
j ['a', 'bcdefghij']
k ['a', 'bcdefghijk']
l ['a', 'bcdefghijkl']
( ['a', 'bcdefghijkl', '']
m ['a', 'bcdefghijkl', 'm']
n ['a', 'bcdefghijkl', 'mn']
o ['a', 'bcdefghijkl', 'mno']
) ['a', 'bcdefghijklonm']
p ['a', 'bcdefghijklonmp']
) ['apmnolkjihgfedcb']
q ['apmnolkjihgfedcbq']
题解:
javascript
/**
* @param {string} s
* @return {string}
*/
var reverseParentheses = function (s) {
let stack = [""];
for (let i = 0; i < s.length; i++) {
let ch = s[i];
if (ch === "(") {
stack.push("");
} else if (ch === ")") {
let str = stack.pop();
let tmp = str.split("").reverse().join("");
stack[stack.length - 1] += tmp;
} else {
stack[stack.length - 1] += ch;
}
}
return stack.pop();
};
cpp
class Solution {
public:
string reverseParentheses(string s) {
stack<string> stk;
string str;
for (auto &ch : s) {
if (ch == '(') {
stk.push(str);
str = "";
} else if (ch == ')') {
reverse(str.begin(), str.end());
str = stk.top() + str;
stk.pop();
} else {
str.push_back(ch);
}
}
return str;
}
};
java
class Solution {
public String reverseParentheses(String s) {
Stack<String> stack = new Stack<>();
StringBuilder str = new StringBuilder();
for (char ch : s.toCharArray()) {
if (ch == '(') {
stack.push(str.toString());
str = new StringBuilder();
} else if (ch == ')') {
str.reverse();
str.insert(0, stack.pop());
} else {
str.append(ch);
}
}
return str.toString();
}
}
python
class Solution:
def reverseParentheses(self, s: str) -> str:
stack = ['']
for ch in s:
if ch == '(':
stack.append('')
elif ch == ')':
stack[-2] += stack.pop()[::-1]
else:
stack[-1] += ch
return stack[0]
javascript
学如逆水行舟,不进则退