前端算法题 判断字符串是否括号匹配
题目:一个字符串 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