Skip to content

Instantly share code, notes, and snippets.

@varnie
Created September 8, 2011 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varnie/1203155 to your computer and use it in GitHub Desktop.
Save varnie/1203155 to your computer and use it in GitHub Desktop.
<?php
function checkBraces($str){
$stack = Array();
for ($i = 0; $i < strlen($str); ++$i) {
$value = $str[$i];
if ($value == '(' || $value == '{'){
array_push($stack, $value);
} else if ($value == ')' || $value == '}'){
if (count($stack) <= 0){
return false;
}else{
$item = array_pop($stack);
if ($value == ')'){
if ($item != '('){
return false;
}
} else if ($value == '}'){
if ($item != '{'){
return false;
}
}
}
}
}
return empty($stack);
}
assert(checkBraces('{(aaaa)}') == true);
assert(checkBraces('()') == true);
assert(checkBraces('{()}') == true);
assert(checkBraces('{()}{}') == true);
assert(checkBraces('{(})') == false);
assert(checkBraces('{}') == true);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment