How to check the sequence of opening and closing brackets in string?

后端 未结 5 823
醉酒成梦
醉酒成梦 2020-12-18 14:42

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

But if don\'t revert right array to compare wit

相关标签:
5条回答
  • 2020-12-18 15:15

    I hope this will solve your problem...

    function brackets(expression) {
        let leftArr=[];
        
        for(let i=0; i<expression.length; i++) {
            if(expression[i] === '(' || expression[i] === '[' || expression[i] === "{") {
                leftArr.push(expression[i]);
            } 
            
            let leftArrLength = leftArr.length;
            
            if(expression[i] === ')' && leftArr[leftArrLength - 1] === '('){
                leftArr.pop();
            }else if(expression[i] === '}' && leftArr[leftArrLength - 1] === '{') {
                leftArr.pop();
            } else if(expression[i] === ']' && leftArr[leftArrLength - 1] === '[') {  
                leftArr.pop();
            }
            else if(expression[i] === ')' || expression[i] === '}' || expression[i] === ']'){
             return false;
            }
        }
    	
        return leftArr.length === 0;
    }
    
    
    
    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
    console.log(brackets('(((([[[[{{{3}}}]]]]))))')); //false

    0 讨论(0)
  • 2020-12-18 15:18

    You can use the function String.prototype.replace to gather the brackets and use a kind of stack to compare each char. The stack is useful in order to know what was the last pushed bracket.

    let check = (e) => {
      let brackets = [],
          stack = [],
          map = {'}': '{', ']': '[', ')': '('};
    
      e.replace(/[\[\]\{\}\(\)]/g, (m) => m && brackets.push(m));
    
      for (let i = 0, {length} = brackets; i < length; i++) {
        if (['}', ']', ')'].includes(brackets[i])) {
          if (stack.pop() !== map[brackets[i]]) return false;
        } else stack.push(brackets[i]);
      }
    
      return !stack.length;
    };
        
        
    console.log(check('(3+{1-1)}')); // false
    console.log(check('{[(3+1)+2]+}')); //true
    console.log(check('[1+1]+(2*2)-{3/3}')); //true
    console.log(check('(({[(((1)-2)+3)-3]/3}-3)')); //false

    0 讨论(0)
  • 2020-12-18 15:19

    You can use stack with switch statement with a single for loop for efficient time and space complexity

    function checkParantesis(str) {
        const stack = [];
        for (let s of str) {
           if (s == '(' || s == '[' || s == '{') {
              stack.push(s);
              continue; 
           }
    
           if (stack.length === 0) {
               return false
           }
    
           switch (s) {
               case ')':
                    stack.pop();
                    if (s == '{' || s == '[') {
                      return false  
                    }
                    break;
               case '}':
                    stack.pop();
                    if (s == '(' || s == '[') {
                      return false  
                    }
                    break;
               case ']':
                    stack.pop();
                    if (s == '{' || s == '(') {
                      return false  
                    }
                    break;
           }
        }
        return stack.length ? false : true
    }
    
    const output = checkParantesis('{{}}'));
    console.log(output)
    
    0 讨论(0)
  • 2020-12-18 15:20

    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
    
    0 讨论(0)
  • 2020-12-18 15:22

    Right now you are getting every single open bracket into one array, then pushing an open bracket for every closing one into another array, then comparing them. That's a bit wasteful.

    Instead, you can maintain a stack. Push an open tag onto the stack and if you find a close bracket - pop from the stack

    • if there is no match or nothing on the stack when you pop, terminate with a failure
    • if you finish with a stack size of zero, then you are successful

    function brackets(expression) {
      let stack = [];
      let current;
      const matchLookup = {
            "(": ")", 
            "[": "]", 
            "{": "}", 
          };
                        
      for (let i = 0; i < expression.length; i++) {
        current = expression[i]; //easier than writing it over and over
        
        if (current === '(' || current === '[' || current === "{") {
          stack.push(current);
          
        } else if (current === ')' || current === ']' || current === "}") {
          const lastBracket = stack.pop();
          
          if (matchLookup[lastBracket] !== current) { //if the stack is empty, .pop() returns undefined, so this expression is still correct
          
            return false; //terminate immediately - no need to continue scanning the string
          }
        }
      }
      
      return stack.length === 0; //any elements mean brackets left open
    }
    
    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

    I have used an object to lookup the values but it need not be one. An alternative is to use two arrays that you have to keep in sync

    opening = ["(", "[", "{"]
    closing = [")", "]", "}"]
    

    On the other hand, if you have those, you can shorten your if checks to if (open.includes(current)) and if (closing.includes(current)).

    0 讨论(0)
提交回复
热议问题