fork download
  1. process.stdin.resume();
  2. process.stdin.setEncoding('utf8');
  3.  
  4.  
  5. function checkMatchedBrackets(testString, brackets = [
  6. '()',
  7. '[]',
  8. '{}'
  9. ]) {
  10. const escapedBrackets = brackets.map((bracketSet) => bracketSet.replace(/(.)/g, '\\$1'));
  11.  
  12. const stripRegexp = new RegExp('[^' + escapedBrackets.join('') + ']', 'g');
  13. const iterativeRegexp = new RegExp('(' + escapedBrackets.join('|') + ')', 'g');
  14.  
  15. let iterativeString = testString.replace(stripRegexp, '');
  16.  
  17. let previousLength = 0;
  18. while (iterativeString.length != previousLength) {
  19. previousLength = iterativeString.length;
  20. iterativeString = iterativeString.replace(iterativeRegexp, '');
  21. }
  22.  
  23. return iterativeString.length === 0;
  24. }
  25.  
  26. [
  27. 'should pass - abc', // No brackets, always passes
  28. 'should pass - a[b]c', // Matches brackets
  29. 'should pass - a(b)c[d]e', // Pair of matched brackets
  30. 'should pass - a(b[c{d(e)f}g]h)i', // Nested correctly
  31. 'should fail - a)b(c', // brackets in the wrong order
  32. 'should fail - a[b(c]d)e', // Bad nesting
  33. 'should fail - a[c' // Unbalanced
  34. ].forEach((testString) => console.log(testString + ' ' + (checkMatchedBrackets(testString) ? 'passed':'failed')));
  35.  
Success #stdin #stdout 0.09s 30176KB
stdin
Standard input is empty
stdout
should pass - abc passed
should pass - a[b]c passed
should pass - a(b)c[d]e passed
should pass - a(b[c{d(e)f}g]h)i passed
should fail - a)b(c failed
should fail - a[b(c]d)e failed
should fail - a[c failed