While I was working, I found a nice puzzle that asked to create a function that matches the braces correctly for {, (, [ with their corresponding braces ], ), }
An example of an expression they provided was the following:
$expressions = array(")(){}","[]({})","([])","{()[]}","([)]");
The values that must be returned are:
0
1
1
1
0
The constraints they provided is that the strings are going to have a maximum a length of 100, and the array may carry at least 50,000 elements. Given those cases, they expect the function to solve the problem in less than 2 seconds.
I tried to write something up, which can be found here (it is incomplete because I felt that this whole if/else method is making it all too hairy - in other words, it would definitely take more than 2 seconds to solve the problem):
https://gist.github.com/adibbehjat/6387415
<?php
function check_braces($expressions) {
for($x = 0; $x < count($expressions); $x++)
{
$open = array("{", "[", "(");
$close = array("}", "]", ")");
$key = array("{" => "}", "[" => "]", "(" => ")");
$string = $expressions[$x];
echo $string."<br>";
//First item should open a brace, else fail
if((in_array($string[0], $close)) && (strlen($string) % 2))
{
echo 0;
echo '<br>';
}
else
{
$bank_o = array();
$bank_c = array();
$element = array();
for($y = 0; $y < strlen($string); $y++)
{
$element = $string[$y];
if(in_array($element, $open))
{
array_push($bank_o, $element);
}
else
{
array_push($bank_c, $element);
}
$arraycounter = array_merge($bank_o, $bank_c);
$y++;
if(!empty($bank_c) && !empty($bank_o))
{
$num = count($bank_o);
if($bank_c[0] == $key[$bank_o[$num - 1]])
{
array_shift($bank_c);
array_pop($bank_o);
}
}
elseif (empty($bank_c) && empty($bank_o)) {
echo 1 . "<br>";
}
else
{
}
}
}
}
}
//$expressions = array(")(){}","[]({})","([])","{()[]}","([)]");
$expressions = array("([])","([)]");
check_braces($expressions);
?>
I learned PHP on my own, and feel that I am lacking a lot of skill in identifying best algorithms to solve such problems. And was curious to see what other alternative methods are possible.