js判断括号匹配算法

逻辑如图

 

代码(栈的类看上一篇):

 function parentheseChecker(symbols){
            const stack = new Stack();
            const opens='([{';
            const closes=')]}';
            let balanced = true;
            let index = 0;
            let symbol;
            let top;

            while(index < symbol.length && balanced){
                symbol = symbols[index];
                if(opens.indexOf(symbol) >= 0){
                    stack.push(symbol)
                } else {
                    if(stack.isEmpty()){
                        balanced =  false;
                    } else {
                        top = stack.pop();
                        if(!(opens.indexOf(top) === closes.indexOf(symbol))){
                            balanced = false
                        }
                    }
                }
                index++; 
            }
            return balanced && stack.isEmpty()

        }

 

posted @ 2022-01-13 15:07  she_will  阅读(225)  评论(0编辑  收藏  举报