判断是否是有效括号
kingcwt2023-09-23前端算法 基础数据结构 面试题
要求
Please write a function to check if the input string which may contain parenthesis is regular. Return true if it is, otherwise false .
Example 1:
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
题解
/** 括号匹配 */
const solution2 = parens =>{
if(parens.length ===0) return true
if(parens.length ===1) return false
let obj = {
")":"("
}
let stack = [];
for(let i=0;i<parens.length;i++){
let item = parens[i];
if(obj[item] ===undefined){
if(item ==='('){
stack.push(item)
}
}else{
if(stack.pop()!==obj[item]){
return false
}
}
}
return stack.length === 0
}
// let s1='(',s2='hi())(',s3='',s4='32423(sgs(show)dg)'
// console.log(solution1(s4))