码迷,mamicode.com
首页 > 其他好文 > 详细

用栈实现字符平衡

时间:2016-04-05 00:33:06      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

今天学了数据结构的栈,里面讲了一个用栈实现字符平衡。用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);

代码很粗糙,没分装,另外只做到了对()[]的判断。

用栈实现字符平衡

标签:

原文地址:http://www.cnblogs.com/wz0107/p/5353211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!