function inArray(arr,ele){
var len=arr.length;
for(var i=0;i<len;i++){
if(ele===arr[i]){
return true;
}
}
return false;
}
function isNest(rule,str){
if(!(rule&&str)){
return false;
}
var keys=[];
var values=[];
for(var key in rule){
if(rule.hasOwnProperty(key)){
keys.push(key);
values.push(rule[key]);
}
}
var chs=str.split("");
var len=chs.length;
var stack=[];
for(var i=0;i<len;i++){
if(inArray(keys,chs[i])){
stack.push(rule[chs[i]]);
}else{
if(chs[i]===stack[stack.length-1]){
stack.pop();
}else if(inArray(values,chs[i])){
return false;
}
}
}
return stack.length===0;
}
var rule={'(':')','[':']','{':'}','<':'>'};
console.log(isNest(rule,"{{sdf(sd[]f)}s }"));
console.log(isNest(rule,"(sdffs"));
console.log(isNest(rule,"sdff)"));
console.log(isNest(rule,"(sdf{sdf}sdf)"));
console.log(isNest(rule,"(sdf}sdf"));
console.log(isNest(rule,"sdf(d{sdf)sd}"));
console.log(isNest(rule));
console.log(isNest());
console.log(isNest(rule,"sdf><(d{sdf)sd}"));
js判断字符串是否是嵌套结构
最新推荐文章于 2022-01-01 12:59:28 发布