Last active
February 5, 2016 15:02
-
-
Save ahsio/e571ca6d3a50140b309f to your computer and use it in GitHub Desktop.
The algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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