老规矩先链接。
力扣1614括号的最大嵌套深度https://leetcode-cn.com/problems/maximum-nesting-depth-of-the-parentheses/题目其实要求的东西很简单,但是描述了非常多的内容。简单题有一个好的地方,测试用例不太会用特别极端的情况,适合前期练手。
本来有自己的想法,但是实现过程中发现存在漏洞,然后看到最末尾的提示:
The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )
某个位置的深度为该位置前面的左括号数量减去该位置前面的右括号数量。
这样解法就很简单了,遍历数组,求每个左括号位置的深度,记录最大深度,遍历结束后返回即可。代码如下:
package cn.daycode.leetcode;
public class MaxDepth {
public static void main(String[] args) {
System.out.println(new Solution().maxDepth("(1)+((2))+(((3)))"));
}
/*
提示:
The depth of any character in the VPS is the
( number of left brackets before it ) - ( number of right brackets before it )
*/
static class Solution {
public int maxDepth(String s) {
int maxDepth = 0; // 记录最大深度
int depth = 0; // 临时记录当前位置的深度
for (int i = 0; i < s.length(); i++) {
// 遇到左括号当前深度+1,然后跟目前最大深度比较,记录其中大者
if (s.charAt(i) == '('){
depth++;
if (depth > maxDepth){
maxDepth = depth;
}
// 遇到右括号当前深度-1
}else if (s.charAt(i) == ')'){
depth--;
}
}
return maxDepth;
}
}
}