欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 最大括号深度

最大括号深度

2024/10/25 8:25:31 来源:https://blog.csdn.net/weixin_64742764/article/details/142009074  浏览:    关键词:最大括号深度

题目描述

现有一字符串仅由'(',')','{','}','[',']'六种括号组成。
若字符串满足以下条件之一,则为无效字符串:

  • ①任一类型的左右括号数量不相等;
  • ②存在未按正确顺序(先左后右)闭合的括号。

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

输入描述

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

输出描述

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

//([]{()})
public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String input = sc.nextLine();System.out.println(maxDepth(input));}public static int maxDepth(String s) {Stack<Character> stack = new Stack<>();int maxDepth = 0;int currentDepth = 0;for (char c : s.toCharArray()) {if (c == '(' || c == '{' || c == '[') {stack.push(c);currentDepth++;maxDepth = Math.max(maxDepth, currentDepth);} else {if (stack.isEmpty()) {return 0;}char top = stack.pop();currentDepth--;if (!isMatch(top, c)) {return 0;}}}return stack.isEmpty() ? maxDepth : 0;}public static boolean isMatch(char left, char right) {return (left == '(' && right == ')') || (left == '{' && right == '}') || (left == '[' && right == ']');}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com