Last active
May 21, 2021 03:44
-
-
Save kangmasjuqi/6ff34bd914e9a82fdf37ae4f486cdfcc to your computer and use it in GitHub Desktop.
Parentheses Validator
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
// Function that tells us whether or not an input string's openers and closers are properly nested. | |
// Examples: | |
// • "{ [ ] ( ) }" should return True | |
// • "{ [ ( ] ) }" should return False | |
// • "{ [ }" should return False | |
function parentheses_validatior($string){ | |
// remove spaces | |
$string = str_replace(' ', '', $string); | |
// turn string into array of chars | |
$arr_char = str_split($string); | |
if(count($arr_char)%2 == 1) | |
return FALSE; | |
$opening_brackets = []; | |
foreach($arr_char as $char){ | |
if(in_array($char, array("{", "(", "["))===TRUE) | |
$opening_brackets[] = $char; | |
else if(in_array($char, array("}", ")", "]"))===TRUE){ | |
$last_idx = count($opening_brackets)-1; | |
if($char == "}" && $opening_brackets[$last_idx] == "{") | |
array_pop($opening_brackets); | |
else if($char == "]" && $opening_brackets[$last_idx] == "[") | |
array_pop($opening_brackets); | |
else if($char == ")" && $opening_brackets[$last_idx] == "(") | |
array_pop($opening_brackets); | |
} | |
} | |
if(count($opening_brackets) == 0) | |
return TRUE; | |
else | |
return FALSE; | |
} | |
$validator1 = parentheses_validatior("{ [ ] ( ) }"); // TRUE | |
var_dump($validator1); | |
$validator2 = parentheses_validatior("{ [ ( ] ) }"); // FALSE | |
var_dump($validator2); | |
$validator3 = parentheses_validatior("{ [ }"); // FALSE | |
var_dump($validator3); | |
$validator4 = parentheses_validatior("{ [{[{}[]{}]}] {} }"); // TRUE | |
var_dump($validator4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment