Skip to content

Instantly share code, notes, and snippets.

@matason
Created April 11, 2021 12:24
Show Gist options
  • Save matason/364762ff3ac72efbca4c39d2ab9af2fc to your computer and use it in GitHub Desktop.
Save matason/364762ff3ac72efbca4c39d2ab9af2fc to your computer and use it in GitHub Desktop.
Calculate maximum nesting depth of parentheses
<?php
/**
* Calculate maximum nesting depth of parentheses.
*
* @see https://www.youtube.com/watch?v=zrOIQEN3Wkk
* @see https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
*/
$input = '(1+(2*3)+((8)/4))+1';
$depth = array_reduce(
array_filter(str_split($input), fn($s) => strstr('()', $s)),
function($carry, $s) {
static $max = 0;
$s === '(' ? $max++ : $max--;
return $max > $carry ? $max : $carry;
});
print_r($depth);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment