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

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

提交回复
热议问题