Skip to content

Instantly share code, notes, and snippets.

@roniemicro
Last active December 16, 2015 02:19
Show Gist options
  • Save roniemicro/5361425 to your computer and use it in GitHub Desktop.
Save roniemicro/5361425 to your computer and use it in GitHub Desktop.
some Simple Implementation of isBalanced function
<?php
function isBalanced($string)
{
$str = preg_replace('([^\(\)])', '', $string);
if($str == ""){
return TRUE;
}
$strArray = str_split($str);
$ImbalanceCounter = 0;
foreach($strArray as $bracket){
$ImbalanceCounter = $bracket == '(' ? $ImbalanceCounter + 1 : $ImbalanceCounter - 1;
if($ImbalanceCounter < 0){
return false;
}
}
return ($ImbalanceCounter == 0);
}
function isBalanced2($string)
{
$cleanStr = preg_replace('([^\(\)])', '', $string);
if($cleanStr == ""){
return TRUE;
}
if(!function_exists('iterate')){
function iterate($str, $count = 0){
if(empty($str)){
return $count == 0;
}else{
$count = substr($str, 0,1) == '(' ? $count + 1 : $count - 1;
return ($count >= 0) ? iterate(substr($str, 1,strlen($str)-1), $count): FALSE;
}
}
}
return iterate($cleanStr);
}
function isBalanced3($str, $count = 0)
{
if (empty($str)) {
return $count == 0;
}
switch ($str[0]) {
case "(" :
$count++;
break;
case ")" :
$count--;
break;
}
return ($count >= 0) ? isBalanced3(substr($str, 1), $count) : FALSE;
}
//Shorter Implementation of Imran vai's Method
function isBalanced4($string){
$str = preg_replace('([^\(\)])', '', $string);
do{
$str = str_replace("()", "", $str, $count);
}while($count>0 && $str!="");
return $str == "";
}
echo "String 1 test: ";
var_dump(isBalanced("balance: '(if (zero? x) max (/ 1 x))' is balanced"));
echo "String 2 test: ";
var_dump(isBalanced2("I told him (that it's not (yet) done)(.\n(But he wasn't listening)"));
echo "String 3 test: ";
var_dump(isBalanced3("())()"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment