/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const n = s.length;
// s长度为奇数一定不闭合
if (n % 2 === 1) {
return false;
}
const pairs = new Map([
[')', '('],
[']', '['],
['}', '{']
]);
const stk = [];
for (let ch of s){
// 如果ch为括号的右部
if (pairs.has(ch)) {
// stk为空 或 stk数组的最后一个元素等于该ch对应的左括号
if (!stk.length || stk[stk.length - 1] !== pairs.get(ch)) {
return false;
}
// 删除数组的最后一个元素
stk.pop();
}
else {
stk.push(ch);
}
};
// stk不为空则为true
return !stk.length;
}