ให้สตริงที่มีเฉพาะอักขระ '(' และ ')' เราจะพบความยาวของสตริงย่อยในวงเล็บที่ถูกต้อง (ที่มีรูปแบบถูกต้อง) ที่ยาวที่สุด
ชุดของวงเล็บมีคุณสมบัติที่จะเป็นวงเล็บที่มีรูปแบบถูกต้อง หากวงเล็บเปิดแต่ละวงเล็บมีวงเล็บปิด
ตัวอย่างเช่น −
'(())()' 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