Skip to content

有效的括号


题解


思路

单调栈

js
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  const len = s.length;

  if (len % 2 !== 0) {
    return false;
  }

  const stack = [];
  const vMap = {
    ')': '(',
    ']': '[',
    '}': '{',
  };

  for (const key in s) {
    if (stack.length > len / 2) {
      return false;
    }

    if (s[key] in vMap) {
      const top = stack.pop();
      if (top !== vMap[s[key]]) {
        return false;
      }
    } else {
      stack.push(s[key]);
    }
  }

  return stack.length === 0;
};
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  const len = s.length;

  if (len % 2 !== 0) {
    return false;
  }

  const stack = [];
  const vMap = {
    ')': '(',
    ']': '[',
    '}': '{',
  };

  for (const key in s) {
    if (stack.length > len / 2) {
      return false;
    }

    if (s[key] in vMap) {
      const top = stack.pop();
      if (top !== vMap[s[key]]) {
        return false;
      }
    } else {
      stack.push(s[key]);
    }
  }

  return stack.length === 0;
};