查找最长的有效括号JavaScript
给定一个仅包含字符'('和')'的字符串,我们找到最长的有效(格式正确)括号子字符串的长度。
一组圆括号有资格成为格式良好的圆括号,只要且仅当每个圆括号包含一个圆括号。
例如-
'(())()' is a well-formed parentheses '())' is not a well-formed parentheses '()()()' is a well-formed parentheses
示例
const str = '(())()(((';
const longestValidParentheses = (str = '') => {
var ts = str.split('');
var stack = [], max = 0;
ts.forEach((el, ind) => {
if (el == '(') {
stack.push(ind);
}
else {
if (stack.length === 0 || ts[stack[stack.length - 1]] == ')'){
stack.push(ind);
}
else {
stack.pop();
};
}
});
stack.push(ts.length);
stack.splice(0, 0, -1);
for (let ind = 0;
ind< stack.length - 1; ind++) {
let v = stack[ind+1] - stack[ind] - 1; max = Math.max(max, v);
};
return max;
}; console.log(longestValidParentheses(str));输出结果
控制台中的输出将是-
6
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短