地址:https://leetcode-cn.com/problems/maximum-nesting-depth-of-the-parentheses/
<?php /** * Created by PhpStorm. * User: huahua * Date: 2020/10/20 * Time: 下午3:20 1614. 括號的最大嵌套深度 如果字符串滿足一下條件之一,則可以稱之爲 有效括號字符串(valid parentheses string,可以簡寫爲 VPS): 字符串是一個空字符串 "",或者是一個不爲 "(" 或 ")" 的單字符。 字符串可以寫爲 AB(A 與 B 字符串連接),其中 A 和 B 都是 有效括號字符串 。 字符串可以寫爲 (A),其中 A 是一個 有效括號字符串 。 類似地,可以定義任何有效括號字符串 S 的 嵌套深度 depth(S): depth("") = 0 depth(A + B) = max(depth(A), depth(B)),其中 A 和 B 都是 有效括號字符串 depth("(" + A + ")") = 1 + depth(A),其中 A 是一個 有效括號字符串 例如:""、"()()"、"()(()())" 都是 有效括號字符串(嵌套深度分別爲 0、1、2),而 ")(" 、"(()" 都不是 有效括號字符串 。 給你一個 有效括號字符串 s,返回該字符串的 s 嵌套深度 。 示例 1: 輸入:s = "(1+(2*3)+((8)/4))+1" 輸出:3 解釋:數字 8 在嵌套的 3 層括號中。 示例 2: 輸入:s = "(1)+((2))+(((3)))" 輸出:3 示例 3: 輸入:s = "1+(2*3)/(2-1)" 輸出:1 示例 4: 輸入:s = "1" 輸出:0 提示: 1 <= s.length <= 100 s 由數字 0-9 和字符 '+'、'-'、'*'、'/'、'('、')' 組成 題目數據保證括號表達式 s 是 有效的括號表達式 */ class Solution { /** * @param String $s * @return Integer */ function maxDepth($s) { $max = 0; $count = 0; for ($i = 0;$i <strlen($s);$i++){ if ($s[$i] == '('){ $count++; }elseif ($s[$i] == ')'){ $count--; }else{ continue; } $max = max($max,$count); } return $max; } }