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

后端 未结 5 853
醉酒成梦
醉酒成梦 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条回答
  •  猫巷女王i
    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)).

提交回复
热议问题