'(' 및 ')' 문자만 포함하는 문자열이 주어지면 가장 긴 유효(잘 구성된) 괄호 부분 문자열의 길이를 찾습니다.
각 여는 괄호에 닫는 괄호가 포함된 경우에만 괄호 세트가 올바른 형식의 괄호가 될 수 있습니다.
예를 들어 -
'(())()' 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