Skip to content

Instantly share code, notes, and snippets.

@lesterchan
Created April 3, 2014 15:07
Show Gist options
  • Save lesterchan/9956115 to your computer and use it in GitHub Desktop.
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 ()[]{}
<?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