function isMatchingPair(str) {
var s = [];
var l = ['(','[','{'];
var r = [')',']','}'];
for(var i = 0; i< str.length; i++){
if(l.includes(str[i]))
s.push(r[l.indexOf(str[i])]);
if(r.includes(str[i]))
if(s.pop()!=str[i]){return false;}
}
return s.length?false:true;
}
Maintain a stack structure, traverse the string, and compare it with the current top of the stack. If the top of the stack is left, the traverser is right, and the brackets are of the same type, they are eliminated. Non-parentheses are ignored.
After traversing, if the stack length is 0, it means there is a match, otherwise it does not match.
function isMatchingPair(str){
var left = /\(|\{|\[/,right = /\)|\}|\]/,map={'(':')','{':'}','[':']'}
var stack = []
var ret = true
str.split('').forEach(function(e){
if(left.test(e)){
stack.push(e)
}else if(right.test(e)){
if(e === map[stack[stack.length - 1]]){
stack.pop()
}else{
ret = false
}
}
})
return ret && !stack.length
}
Stack structure bracket matching.
Maintain a stack structure, traverse the string, and compare it with the current top of the stack. If the top of the stack is left, the traverser is right, and the brackets are of the same type, they are eliminated. Non-parentheses are ignored.
After traversing, if the stack length is 0, it means there is a match, otherwise it does not match.
Wow, can you ask where the interview questions are? It still feels not easy