查找最长的有效括号 JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/2 22:04:17
给定一个仅包含字符 '(' 和 ')' 的字符串,我们找到最长的有效(格式正确的)括号子字符串的长度。
当且仅当每个左括号都包含一个右括号时,一组括号才有资格成为格式正确的括号。
例如 −
'(())()' 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

