Given a string containing just the characters
"("and")", find the length of the longest valid(well-formed) parentheses substring.
Input = "(()"
Output = 2
Explanation: The longest valid parentheses substring is "()"
Input = ")()())"
Output = 4
Explanation: The longest valid parentheses substring is "()()"
Brute force로 풀면 시간 복잡도가 O(n^3) 이므로 좀 더 효율적인 방법을 찾아보자.
-1을 넣어준다."("을 만나면 stack에 해당 index를 넣어준다.")"인 경우 stack의 element 하나를 제거한다. 그 다음:는 나중에...
/**
 * @param {string} s
 * @return {number}
 */
var longestValidParentheses = function (s) {
  const stack = [-1];
  let maxLength = 0;
  for (let i = 0; i < s.length; i++) {
    if (s[i] === "(") {
      stack.push(i);
    } else if (s[i] === ")") {
      stack.pop();
      if (stack.length) {
        const length = i - stack[stack.length - 1];
        maxLength = Math.max(maxLength, length);
      } else {
        stack.push(i);
      }
    }
  }
  return maxLength;
};
Stack을 한차례 순회하면 끝이므로 O(n)의 시간복잡도로 문제를 해결할 수 있다.
Input string외에 n과 비례하는 공간을 차지하는 stack을 필요로 하므로 O(n)의 공간복잡도를 가진다.