算法题判断字符串是否括号匹配前端算法题判断字符串是否括号匹配
题⽬:⼀个字符串 str 可能包含{},(),[]三种括号。判断 str 是否是括号匹配的
如:(a{b}c) 匹配,⽽ {a(b}c) 是不匹配的
思路:⽤栈的思想
遇到左括号 { [ ( 就压栈
遇到右括号 } ] ) 就判断栈顶,匹配则出栈
左后判断栈的长度是否为0,为0则说明匹配
function matchBracket(str){
const length = str.length
if (length === 0) return true
const stack = [] //建⽴⼀个栈
const leftSymbols = '{[(<'
const rightSymbols = '}])>'
for(let i = 0;i < length;i++){
const s = str[i]
//字符串⾥有左括号,压栈
if(leftSymbols.includes(s)){
stack.push(s)
}else if(rightSymbols.includes(s)){
//字符串⾥有右括号,判断与栈顶是否匹配,匹配就出栈
const top = stack[stack.length-1]
if(isMatch(top,s)){
stack.pop()
}else{
return false
}
}
}
return stack.length === 0
}
const isMatch = (left,right)=>{
if(left == '{' && right == '}') return true
if(left == '[' && right == ']') return true
正则匹配尖括号
if(left == '(' && right == ')') return true
if(left == '<' && right == '>') return true
return false
}
//功能测试
const str = '{a{a<a>a}a}'
console.log(matchBracket(str))//true

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。