This is a continuation of this question, at least the first part of that question. I want to check if everything in the new code is right or if there are other way to make it better.
Exercise
The validBraces
method takes a string of braces as a single parameter and determines if the order of the braces is valid. All input strings will only consist of open curly braces {
, closed curly braces }
, open parentheses (
, closed parentheses )
, and open brackets [
and closed brackets ]
.
- A string of braces is considered valid if all open braces are matched with their corresponding closed brace. For example:
(){}[]
and([{}])
would be considered valid, while(}
,[(])
, and[({})](]
would be considered invalid. - An empty string is considered valid.
- A non-string input is considered an invalid input. The method should throw an
InvalidArgumentException
in this case.
class StringUtil {
public function validBraces($braces) {
if ($braces === "") {
return true;
} elseif (!is_string($braces)) {
throw new InvalidArgumentException("Not a string");
}
$balance = array();
for ($i = 0; $i < strlen($braces); $i++) {
//allowed chars (){}[]
if (!($braces[$i] === "(" || $braces[$i] === ")"
|| $braces[$i] === "{" || $braces[$i] === "}"
|| $braces[$i] === "[" || $braces[$i] === "]")) {
throw new InvalidArgumentException("Invalid string");
} elseif ($braces[$i] === "(" || $braces[$i] === "{" || $braces[$i] === "[") {
array_push($balance, $braces[$i]);
} elseif ($braces[$i] === ")") {
if (array_pop($balance) !== "(") {
return false;
}
} elseif ($braces[$i] === "}") {
if (array_pop($balance) !== "{") {
return false;
}
} elseif ($braces[$i] === "]") {
if (array_pop($balance) !== "[") {
return false;
}
}
}
if (count($balance) == 0) {
return true;
}
return false;
}
}