[JavaScript 刷题] 栈 - 有效的括号, leetcode 20

[JavaScript 刷题] 栈 - 有效的括号, leetcode 20

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:20. Valid Parentheses

题目

如下:

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

解题思路

一道经典题,主要核心思想就是利用栈的 FILO 的特性,每次遇到 }, ], 和 ) 都检查一下是否与栈中最后一个元素是一对,否则就是不合法的状态。

唯一需要注意的一点就是,返回值需要判断栈是否为空,因为有可能会出现出现了一次的开括号,但是没有对应的闭括号这种情况。

使用 JavaScript 解题

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
    
    
  const map = {
    
    
      "}": "{",
      ")": "(",
      "]": "[",
    },
    stack = [];

  for (const ch of s) {
    
    
    if (ch === "(" || ch === "{" || ch === "[") {
    
    
      stack.push(ch);
      continue;
    }

    if (map[ch] !== stack.pop()) return false;
  }

  return stack.length === 0;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125755212