js实现有效括号(letcode20)
作者:互联网
方式一
var isValid = function (s) {
if (s.length <= 1 || s.length % 2 != 0) return false
let length = s.length
for(let i = 0; i <= length -1; i++) {
s= s.replace("()", "")
s= s.replace("[]", "")
s= s.replace("{}", "")
if(s.length == 0) {
return true
}
}
if(s.length != 0) {
return false
}else {
return true
}
};
// 方式二
function isValid(s) {
if (s.length = 1) return false
let A = s.length
for (let i = 0; i < A; i++) {
if (s.indexOf("()") > -1 || s.indexOf("{}") > -1 || s.indexOf("[]") > -1) {
s = s.replace("()", "");
s = s.replace("{}", "")
s = s.replace("[]", "")
} else {
break
}
}
if (s == "") { return true } else {
return false
}
}
isValid("(([]){})")
标签:return,else,isValid,letcode20,indexOf,replace,括号,length,js 来源: https://blog.csdn.net/CarryNo1/article/details/121033309