Created
April 3, 2014 15:07
-
-
Save lesterchan/9956115 to your computer and use it in GitHub Desktop.
Use a stack to check whether the parentheses in a string is balanced ()[]{}
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 | |
function is_pair($open, $close) | |
{ | |
if($open == '(' && $close == ')') return true; | |
elseif($open == '{' && $close == '}') return true; | |
elseif($open == '[' && $close == ']') return true; | |
return false; | |
} | |
function balance($test) | |
{ | |
$stack = array(); | |
for($i = 0; $i < strlen($test); $i++) | |
{ | |
$char = $test[$i]; | |
if(in_array($char, array('(', '[', '{'))) | |
{ | |
array_push($stack, $char); | |
} | |
elseif(in_array($char, array(')', ']', '}'))) | |
{ | |
if(empty($stack) || !is_pair(end($stack), $char)) | |
{ | |
return false; | |
} | |
else | |
{ | |
array_pop($stack); | |
} | |
} | |
} | |
return empty($stack) ? true : false; | |
} | |
$tests = array('[{()}]', '[{([)}]', '[{]', '[]', '[', ']', '[{(}]', '([][]){}'); | |
foreach($tests as $test) | |
{ | |
echo $test.' - '; | |
if(balance($test)) | |
echo 'true'; | |
else | |
echo 'false'; | |
echo "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment