[230830] Leetcode - 20

Leetcode - 20, Valid Parentheses

  • 20. Valid Parentheses
  • 스택 사용
  • JS 에서는 배열을 stack 처럼 사용 가능하다.
  • 시간 복잡도 O(n), 공간 복잡도 O(n)
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  const stack = [];

  const compareHelper = (a, b) => {
    if (a === "(" && b === ")") return true;
    if (a === "[" && b === "]") return true;
    if (a === "{" && b === "}") return true;

    return false;
  };

  for (const char of s) {
    if (char === "(" || char === "{" || char === "[") stack.push(char);
    else {
      if (!stack.length) return false;

      const compareChar = stack.pop();
      if (!compareHelper(compareChar, char)) return false;
    }
  }

  return !stack.length;
};

Categories:

Updated:

Leave a comment