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

后端 未结 5 849
醉酒成梦
醉酒成梦 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: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

提交回复
热议问题