Created
April 11, 2021 12:24
-
-
Save matason/364762ff3ac72efbca4c39d2ab9af2fc to your computer and use it in GitHub Desktop.
Calculate maximum nesting depth of parentheses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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