Skip to content

Instantly share code, notes, and snippets.

@ahsio
Last active February 5, 2016 15:02
Show Gist options
  • Save ahsio/e571ca6d3a50140b309f to your computer and use it in GitHub Desktop.
Save ahsio/e571ca6d3a50140b309f to your computer and use it in GitHub Desktop.
The algorithm
<?php
function check($str) {
$length = strlen($str);
$rules = array('NULL', '()', '[]', '[NULL]','(NULL)', '()[]');
$i = 0;
while ($i <= $length/2) {
foreach ($rules as $rule) {
$str = str_replace($rule, '', $str);
}
if (empty($str)) {
return true;
}
$i++;
}
return false;
}
assert(check('') === TRUE, '[()] => TRUE');
assert(check('[()]') === TRUE, '[()] => TRUE');
assert(check('(()[])') === TRUE,'(()[]) => TRUE');
assert(check('([)]') === FALSE, '([)] => FALSE');
assert(check('((') === FALSE, '(( => FALSE');
assert(check('[(()])') === FALSE, '[(()]) => FALSE');
assert(check("([(([[(([]))]]))])") === TRUE, "([(([[(([]))]]))]) => TRUE");
assert(check("[](()()[[]])()[]([])") === TRUE, "[](()()[[]])()[]([]) => TRUE");
assert(check("([((([(([]))])))))])") === FALSE, "([((([(([]))])))))]) => FALSE");
assert(check("[](()()[[]])[][[([])") === FALSE, "[](()()[[]])[][[([]) => FALSE");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment