Last active
October 16, 2018 10:42
-
-
Save demyanovs/ef6c17ff062f59d12fe9bbf34892a896 to your computer and use it in GitHub Desktop.
Check brackets for balance
This file contains hidden or 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 | |
/** | |
* User: vyacheslav.demyanov | |
* Check brackets for balance | |
* [([]{[]})] — balanced, but {[}], [{)] and ]{}[ - not. | |
*/ | |
if (isset($argv[1])) { | |
$str = $argv[1]; | |
} else { | |
$str = '[([]{[]})]'; | |
} | |
echo "Checking string: $str\n"; | |
echo "Is balanced: ".(int)isBalanced($str)."\n"; | |
function isBalanced($str) { | |
$stack = []; | |
for ($i = 0; $i < strlen($str); $i++) { | |
if (in_array($str[$i], ['(', '[', '{'])) { | |
$stack[] = $str[$i]; | |
} else { | |
$last = array_pop($stack); | |
if ($str[$i] != invert($last)) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
function invert($bracket) { | |
$inverse = false; | |
switch ($bracket) { | |
case '(': | |
$inverse = ')'; | |
break; | |
case '[': | |
$inverse = ']'; | |
break; | |
case '{': | |
$inverse = '}'; | |
break; | |
} | |
return $inverse; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment