12、最大括号深度——华子机试必知必会

126 阅读1分钟

题目描述

现有一字符串仅由 ( ) { } [ ]六种括号组成。

若字符串满足以下条件之一,则为无效字符串:

①任一类型的左右括号数量不相等;

②存在未按正确顺序(先左后右)闭合的括号。

输出括号的最大嵌套深度,若字符串无效则输出0。

0≤字符串长度≤100000

输入描述

一个只包括 ( ) { } [ ]的字符串

输出描述

一个整数,最大的括号深度

示例1

输入

[]

输出

1

说明:有效字符串,最大嵌套深度为1。

示例2

输入

([)]

输出

0

说明:无效字符串,存在未按正确顺序闭合的括号

示例3

输入

([]{()})

输出

3

说明:有效字符串,最大嵌套深度为3

示例4

输入

)(

输出

0

说明:无效字符串,存在未按正确顺序闭合的括号

题解

 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串:");
        String input = sc.nextLine();
        System.out.println(maxDepth(input));
    }

    public static int maxDepth(String input) {
        Stack<Character> stack = new Stack<>();
        int depth = 0;
        for (char c : input.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else if (c == ')' || c == '}' || c == ']') {
                if (stack.isEmpty()) {
                    return 0;
                }
                char top = stack.pop();
                //未按正确顺序闭合的括号则为无效字符串
                if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
                    return 0;
                }
                //深度取较大值
                depth = Math.max(depth, stack.size() + 1);
            }
        }
        if (!stack.isEmpty()) {
            return 0;
        }
        return depth;
    }