/**
*
* @param s string字符串
* @return bool布尔型
*/
function isValid(s) {
// write code here
let cnt = [0, 0, 0];
let len = s.length;
// 映射值
function check(s) {
switch (s) {
case "(": return 0;
case "[": return 1;
case "{": return 2;
case ")": return 3;
case "]": return 4;
case "}": return 5;
}
}
let lastIndex = [];
for (let i = 0; i < len; ++i) {
let index = check(s[i]);
if (index < 3) {
cnt[index]++;
// 记录左括号
lastIndex.push(index);
} else {
index -= 3;
// 取出左括号
let cur = lastIndex.pop();
// 若左右括号非配对,则返回false
if (cur != index) {
return false;
}
cnt[index]--;
}
}
let flag = true;
// 遍历统计数组
for (let i = 0; i < 3; ++i) {
if (cnt[i] != 0) {
// 若有一种括号没有用完,则返回false
flag = false;
}
}
return flag;
}
module.exports = {
isValid: isValid
};