整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦
匹配括号字符串
给定一个包括"(","{","[","]","}",")"的字符串,判断是否有效,有效字符串需满足
1.做括号必须用相同类型的右括号闭合
2.左括号必须以正常顺序闭合
采用入栈出栈的方式实现
function test(str) {
let temp
let res = []
strArr = str.match(/(\(|\)|\{|\}|\[|\]){1}/g)
while (temp = strArr.shift()) {
switch (temp) {
case "(":
res.push(temp);
break;
case "{":
res.push(temp);
break;
case "[":
res.push(temp);
break;
case ")":
res[res.length - 1] === "("?res.pop():res.push(temp)
break;
case "}":
res[res.length - 1] === "{"?res.pop():res.push(temp)
break;
case "]":
res[res.length - 1] === "["?res.pop():res.push(temp)
break;
}
}
return res.length === 0
}