21xrx.com
2025-03-26 09:20:24 Wednesday
文章检索 我的文章 写文章
Java实现最大括号深度算法
2023-06-16 21:49:49 深夜i     10     0
Java 括号深度 算法

文章:

在计算机编程中,括号深度是指括号嵌套的深度。例如,在字符串“((()))”中,括号的深度为3。为了找出一个给定字符串中最大括号深度,可以使用Java编写算法。

示例代码如下:

public static int getMaxDepth(String s) {
  int maxDepth = 0;
  int currentDepth = 0;
  for (char c : s.toCharArray()) {
    if (c == '(') {
      currentDepth++;
      if (currentDepth > maxDepth)
        maxDepth = currentDepth;
      
    } else if (c == ')') {
      if (currentDepth > 0)
        currentDepth--;
       else
        return -1; //不合法
      
    }
  }
  if (currentDepth != 0)
    return -1; //不合法
  
  return maxDepth;
}

该算法通过遍历给定字符串,统计左括号和右括号的数量,计算最大深度。如果计算过程中遇到右括号比左括号多的情况,说明该字符串不合法。如果计算结束后,左右括号数量不相等,则该字符串同样不合法。

这个算法非常简单且高效。如果需要计算多个字符串的最大括号深度,可以将该算法封装在一个方法中,并对每个字符串调用一次该方法即可。

  
  

评论区

请求出错了