function isParenthesisMatching($string) {
$openingClosingMatchSymbols = ['(' => ')', '{' => '}', '[' => ']'];
$closingSymbolOpeningMatch = array_flip($openingClosingMatchSymbols);
$stack = [];
for($i=0, $c = strlen($string); $i < $c; $i++) {
$char = $string[$i];
if(array_key_exists($char, $openingClosingMatchSymbols)) {
array_push($stack, $char);
} else {
if(count($stack) === 0) {
return false;
}
else if($closingSymbolOpeningMatch[$char] === end($stack)) {
array_pop($stack);
}
}
}
return empty($stack);
}
$string = "{[({})]}";
var_dump(isParenthesisMatching($string));
$string = "[{{}}]]";
var_dump(isParenthesisMatching($string));
$string = "[]]";
var_dump(isParenthesisMatching($string));
$string = "[{{}";
var_dump(isParenthesisMatching($string));
$string = "[]";
var_dump(isParenthesisMatching($string));
// ouput:
// bool(true)
// bool(false)
// bool(false)
// bool(false)
// bool(true)
Subscribe
Login
0 Comments
Most Voted