算法练习-最大括号深度

题目:

如果字符串满足以下条件之一,则可以称之为 有效括号字符串(valid parentheses string,可以简写为 VPS):

  • 字符串是一个空字符串 "",或者是一个不为 "(" 或 ")" 的单字符。

  • 字符串可以写为 AB(A 与 B 字符串连接),其中 A 和 B 都是 有效括号字符串 。

  • 字符串可以写为 (A),其中 A 是一个 有效括号字符串 。

类似地,可以定义任何有效括号字符串 S 的 嵌套深度 depth(S):

  • depth("") = 0
  • depth(C) = 0,其中 C 是单个字符的字符串,且该字符不是 "(" 或者 ")"
  • depth(A + B) = max(depth(A), depth(B)),其中 A 和 B 都是 有效括号字符串
  • depth("(" + A + ")") = 1 + depth(A),其中 A 是一个 有效括号字符串

例如:""、"()()"、"()(()())" 都是 有效括号字符串(嵌套深度分别为 0、1、2),而 ")(" 、"(()" 都不是 有效括号字符串 。

给你一个 有效括号字符串 s,返回该字符串的 s 嵌套深度 。

public class Kuohao {

    public static void main(String[] args) {
        String str = "{}()[]((()){})";
        char[] chars = str.toCharArray();
        //使用栈结构,匹配的话,最终栈的深度就是0,中途栈最深的的时候就是深度的最大值
        Stack<Character> stack = new Stack<>();
        int max = 0;
        int result = 0 ;
        for (Character ch : chars) {
            if (stack.size() > 0 ){
                Character temp = stack.peek();
                if (temp != null && checkBoth(temp,ch)){
                    stack.pop();
                    max = max - 1;
                } else {
                    stack.push(ch);
                    max = max +1 ;
                }
            } else {
                stack.push(ch);
                max = max +1 ;
            }
            if (max > result){
                result = max ;
            }
        }
        if (max != 0){
            System.out.println("字符串不合法");
        }
        System.out.println("最大深度:" + result);
    }

    static public boolean checkBoth(Character a ,Character b){
        if (a.equals('(')&&b.equals(')')){
            return true;
        }
        if (a.equals('[')&&b.equals(']')){
            return true;
        }
        if (a.equals('{')&&b.equals('}')){
            return true;
        }


        return false;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笔下天地宽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值