今天学了数据结构的栈,里面讲了一个用栈实现字符平衡。用JS实现了下
//step1 => declare a stack and a str for test and a flag for final check var stack=[], str="(123)iasd[123]]", flag=true; //step2 => for loop and push the left-part into stack; strlen=str.length; for(var i=0;i<strlen;i++){ if(str[i]==‘(‘ || str[i]==‘[‘){ stack.push(str[i]); } //step3 => test if the character is suited to the top of stack; var stacklen=stack.length; //step4 => suited and pop the top of stack; //step5 => not suited and change the flag if(str[i]==‘)‘ && stack[stacklen-1]!=‘(‘){ flag=false; } if(str[i]==‘]‘ && stack[stacklen-1]!=‘[‘){ flag=false; } if(str[i]==‘)‘ && stack[stacklen-1]==‘(‘){ stack.pop(); } if(str[i]==‘]‘ && stack[stacklen-1]==‘[‘){ stack.pop(); } } // step6 => after the loop,if the stack have elements,change the flag to false; if(stack.length){ flag=false; } //step7 => check out flag; alert(flag);
代码很粗糙,没分装,另外只做到了对()[]的判断。
时间: 2024-10-03 14:45:26