PHP Nesting
function nesting(string $s): int
{
if (empty($s)) {
return 1;
}
$stack = [];
foreach (str_split($s) as $v) {
if ($v === ')') {
if (empty($stack) || array_pop($stack) !== '(') {
return 0;
}
} elseif ( ! empty($v)) {
$stack[] = $v;
}
}
return empty($stack) ? 1 : 0;
}
This treats the string like a balance counter: open parentheses add one, closing ones remove one.