[JavaScript 刷题] 栈 - 有效的括号, leetcode 20
github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。
题目
如下:
Given a string
s
containing just the characters'('
,')'
,'{'
,'}'
,'['
and']'
, determine if the input string is valid.An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- 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;
};