20 Valid Parentheses

有效的括号,栈实现

  • 时间复杂度O(n),空间复杂度O(n)
  • Runtime: 60 ms, faster than 99.63%
  • Memory Usage: 40.2 MB, less than 27.23%
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
  const map = {
    '}': '{',
    ']': '[',
    ')': '('
  }
  const stack = [];
  for (let item of s) {
    if (map[item]) {    
      if (stack[stack.length - 1] === map[item]) {
        stack.pop();
      } else {
        return false;
      }
    } else {
      stack.push(item);
    }
  }
  return stack.length === 0;
};

你可能感兴趣的:(20 Valid Parentheses)