Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2712
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

30条回答
  •  粉色の甜心
    2020-11-27 12:18

    I tried this using javascript below is the result.

    function bracesChecker(str) {
      if(!str) {
        return true;
      }
      var openingBraces = ['{', '[', '('];
      var closingBraces = ['}', ']', ')'];
      var stack = [];
      var openIndex;
      var closeIndex;
      //check for opening Braces in the val
      for (var i = 0, len = str.length; i < len; i++) {
        openIndex = openingBraces.indexOf(str[i]);
        closeIndex = closingBraces.indexOf(str[i]);
        if(openIndex !== -1) {
          stack.push(str[i]);
        }  
        if(closeIndex !== -1) {
          if(openingBraces[closeIndex] === stack[stack.length-1]) { 
            stack.pop();
          } else {
            return false;
          }
        }
      }
      if(stack.length === 0) {
        return true;
      } else {
        return false;
      }
    }
    var testStrings = [
      '', 
      'test', 
      '{{[][]()()}()}[]()', 
      '{test{[test]}}', 
      '{test{[test]}', 
      '{test{(yo)[test]}}', 
      'test{[test]}}', 
      'te()s[]t{[test]}', 
      'te()s[]t{[test'
    ];
    
    testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`));
    

提交回复
热议问题