如何检查字符串中打开和关闭括号的顺序? [英] How to check the sequence of opening and closing brackets in string?

查看:30
本文介绍了如何检查字符串中打开和关闭括号的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要查找左括号和右括号,如果违反了右括号的顺序,则返回false.

Need to find open and closed bracket, if the sequence of opening and closing brackets is violated, then return false.

但是,如果不还原右数组以与左数组进行比较,则我不在此处做方括号 {[((3 + 1)+2] +} .如果像现在这样反向,那么我无法在此处检查 [1 + 1] +(2 * 2)-{3/3}

But if don't revert right array to compare with left array, i don't make check brackets here {[(3+1)+2]+}. And if reverse like now, then i fail to check here [1+1]+(2*2)-{3/3}

function brackets(expression){
    let leftArr=[];
    let rightArr = [];
    for(let i=0; i<expression.length; i++){
    		if(expression[i] === '(' || expression[i] === '[' || expression[i] === "{"){
        	leftArr.push(expression[i]);
        }
        
        
        if(expression[i] === ')'){
      
        		rightArr.push("(");
        }else if(expression[i] === '}'){
        
        		rightArr.push("{");
        } else if(expression[i] === ']'){
        
        		rightArr.push("[");
        }
   }
		
   rightArr.reverse();
    
    if(leftArr.length<rightArr.length || leftArr.length>rightArr.length){
    return false;
    }
    
    for(let k=0; k<leftArr.length; k++) {
    		if(leftArr[k] != rightArr[k]){
        		return false;
        }
    }

    return true;
}



console.log(brackets('(3+{1-1)}')); // false
console.log(brackets('{[(3+1)+2]+}')); //true
console.log(brackets('[1+1]+(2*2)-{3/3}')); //true
console.log(brackets('(({[(((1)-2)+3)-3]/3}-3)')); //false

推荐答案

在最短的时间内加上注释,可能会使您感到困惑.

In the shortest possible, with comments for lines that are probably confusing for you.

function check(expr){
    const holder = []
    const openBrackets = ['(','{','[']
    const closedBrackets = [')','}',']']
    for (let letter of expr) { // loop trought all letters of expr
        if(openBrackets.includes(letter)){ // if its oppening bracket
            holder.push(letter)
        }else if(closedBrackets.includes(letter)){ // if its closing
            const openPair = openBrackets[closedBrackets.indexOf(letter)] // find its pair
            if(holder[holder.length - 1] === openPair){ // check if that pair is the last element in the array
                holder.splice(-1,1) // if so, remove it
            }else{ // if its not
                holder.push(letter)
                break // exit loop
            }
        }
    }
    return (holder.length === 0) // return true if length is 0, otherwise false
}
check('[[{asd}]]') /// true

这篇关于如何检查字符串中打开和关闭括号的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆