1190. 反转每对括号间的子串(栈)
题目来源:1190. 反转每对括号间的子串
给出一个字符串 s(仅含有小写英文字母和括号)。
请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
注意,您的结果中 不应 包含任何括号。
/** * @param {string} s * @return {string} */ var reverseParentheses = function(s) { let stack = []; let str = ''; for(let c of s){ if(c === '('){ stack.push(str); str=''; }else if(c === ')'){ str = str.split('').reverse().join(''); str = stack.pop() + str; }else{ str += c; } } return str; }; let s = "a(bcdefghijkl(mno)p)q" console.log(s, reverseParentheses(s)); s = "(ed(et(oc))el)" console.log(s, reverseParentheses(s)); s = "sxmdll(q)eki(x)" console.log(s, reverseParentheses(s)); //方法二:预处理括号 var reverseParentheses = function(s) { let n = s.length; let stack = []; let pair = new Array(n).fill(0); let str = ''; let step = 1; let index = 0; for(let i=0;i<n;i++){ if(s[i] === '('){ stack.push(i); }else if(s[i] === ')'){ let j = stack.pop(); pair[i] = j; pair[j] = i; } } while(index<n){ if(s[index] === '(' || s[index] === ')'){ index = pair[index]; step = -step; }else{ str += s[index]; } index += step; } return str; }; s = "a(bcdefghijkl(mno)p)q" console.log(s, reverseParentheses(s)); s = "(ed(et(oc))el)" console.log(s, reverseParentheses(s)); s = "sxmdll(q)eki(x)" console.log(s, reverseParentheses(s));
示例 1:
输入:s = "(abcd)"
输出:"dcba"
示例 2:
输入:s = "(u(love)i)"
输出:"iloveu"
示例 3:
输入:s = "(ed(et(oc))el)"
输出:"leetcode"
示例 4:
输入:s = "a(bcdefghijkl(mno)p)q"
输出:"apmnolkjihgfedcbq"
提示:
0 <= s.length <= 2000
s 中只有小写英文字母和括号
我们确保所有括号都是成对出现的