【每日一题】Day0018:力扣题库NO.1614. 括号的最大嵌套深度(java实现)

老规矩先链接。

力扣1614括号的最大嵌套深度icon-default.png?t=LBL2https://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;
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值