📜  查找字符串中嵌套括号的最大深度

📅  最后修改于: 2022-05-13 01:57:07.926000             🧑  作者: Mango

查找字符串中嵌套括号的最大深度

我们得到一个带有括号的字符串,如下所示
“(((X))(((Y))))”
我们需要找到平衡括号的最大深度,如上例中的 4。因为 'Y' 被 4 个平衡的括号包围。
如果括号不平衡,则返回-1。

例子 :

Input : S = "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)";
Output : 4

Input : S = "( p((q)) ((s)t) )";
Output : 3

Input : S = "";
Output : 0

Input : S = "b) (c) ()";
Output : -1 

Input : S = "(b) ((c) ()"
Output : -1 

方法一(使用堆栈)
一个简单的解决方案是使用一个跟踪当前开括号的堆栈。

1) Create a stack. 
2) Traverse the string, do following for every character
     a) If current character is ‘(’ push it to the stack .
     b) If character is ‘)’, pop an element.
     c) Maintain maximum count during the traversal. 

下面是算法的代码实现。

C++
// A C++ program to find the maximum depth of nested
// parenthesis in a given expression
#include 
using namespace std;
 
int maxDepth(string& s)
{
    int count = 0;
    stack st;
 
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '(')
            st.push(i); // pushing the bracket in the stack
        else if (s[i] == ')') {
            if (count < st.size())
                count = st.size();
            /*keeping track of the parenthesis and storing
            it before removing it when it gets balanced*/
            st.pop();
        }
    }
    return count;
}
 
// Driver program
int main()
{
    string s = "( ((X)) (((Y))) )";
    cout << maxDepth(s);
 
    // This code is contributed by rakeshsahni
 
    return 0;
}


Java
/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
class GFG {
    public static int maxDepth(String s) {
        int count=0;
        Stack st = new Stack<>();
         
        for(int i=0;i


C++
// A C++ program to find the maximum depth of nested
// parenthesis in a given expression
#include 
using namespace std;
 
// function takes a string and returns the
// maximum depth nested parenthesis
int maxDepth(string S)
{
    int current_max = 0; // current count
    int max = 0; // overall maximum count
    int n = S.length();
 
    // Traverse the input string
    for (int i = 0; i < n; i++)
    {
        if (S[i] == '(')
        {
            current_max++;
 
            // update max if required
            if (current_max > max)
                max = current_max;
        }
        else if (S[i] == ')')
        {
            if (current_max > 0)
                current_max--;
            else
                return -1;
        }
    }
 
    // finally check for unbalanced string
    if (current_max != 0)
        return -1;
 
    return max;
}
 
// Driver program
int main()
{
    string s = "( ((X)) (((Y))) )";
    cout << maxDepth(s);
    return 0;
}


Java
//Java program to find the maximum depth of nested
// parenthesis in a given expression
 
class GFG {
// function takes a string and returns the
// maximum depth nested parenthesis
 
    static int maxDepth(String S) {
        int current_max = 0; // current count
        int max = 0; // overall maximum count
        int n = S.length();
 
        // Traverse the input string
        for (int i = 0; i < n; i++) {
            if (S.charAt(i) == '(') {
                current_max++;
 
                // update max if required
                if (current_max > max) {
                    max = current_max;
                }
            } else if (S.charAt(i) == ')') {
                if (current_max > 0) {
                    current_max--;
                } else {
                    return -1;
                }
            }
        }
 
        // finally check for unbalanced string
        if (current_max != 0) {
            return -1;
        }
 
        return max;
    }
 
// Driver program
    public static void main(String[] args) {
        String s = "( ((X)) (((Y))) )";
        System.out.println(maxDepth(s));
    }
}


Python3
# A Python program to find the maximum depth of nested
# parenthesis in a given expression
 
# function takes a string and returns the
# maximum depth nested parenthesis
def maxDepth(S):
    current_max = 0
    max = 0
    n = len(S)
 
    # Traverse the input string
    for i in range(n):
        if S[i] == '(':
            current_max += 1
 
            if current_max > max:
                max = current_max
        else if S[i] == ')':
            if current_max > 0:
                current_max -= 1
            else:
                return -1
 
    # finally check for unbalanced string
    if current_max != 0:
        return -1
 
    return max
 
# Driver program
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
 
# This code is contributed by BHAVYA JAIN


C#
// C# program to find the
// maximum depth of nested
// parenthesis in a given expression
using System;
class GFG {
   
// function takes a string
// and returns the maximum
// depth nested parenthesis
 
static int maxDepth(string S)
{
  // current count
  int current_max = 0;
   
  // overall maximum count
  int max = 0;
   
  int n = S.Length;
 
  // Traverse the input string
  for (int i = 0; i < n; i++)
  {
    if (S[i] == '(')
    {
      current_max++;
 
      // update max if required
      if (current_max > max)
      {
        max = current_max;
      }
    }
    else if (S[i] == ')')
    {
      if (current_max > 0)
      {
        current_max--;
      }
      else
      {
        return -1;
      }
    }
  }
 
  // finally check for unbalanced string
  if (current_max != 0)
  {
    return -1;
  }
 
  return max;
}
 
// Driver program
public static void Main()
{
  string s = "(((X)) (((Y))))";
  Console.Write(maxDepth(s));
}
}
 
// This code is contributed by Chitranayal


PHP
 $max)
                $max = $current_max;
        }
         
        else if ($S[$i] == ')')
        {
            if ($current_max>0)
                $current_max--;
            else
                return -1;
        }
    }
 
    // finally check for
    // unbalanced string
    if ($current_max != 0)
        return -1;
 
    return $max;
}
 
// Driver Code
$s = "( ((X)) (((Y))) )";
echo maxDepth($s);
 
// This code is contributed by mits
?>


Javascript


输出
4

时间复杂度:O(n)
辅助空间:O(n)

方法2(O(1)辅助空间)
这也可以在不使用堆栈的情况下完成。

1) Take two variables max and current_max, initialize both of them as 0.
2) Traverse the string, do following for every character
    a) If current character is ‘(’, increment current_max and 
       update max value if required.
    b) If character is ‘)’. Check if current_max is positive or
       not (this condition ensure that parenthesis are balanced). 
       If positive that means we previously had a ‘(’ character 
       so decrement current_max without worry. 
       If not positive then the parenthesis are not balanced. 
       Thus return -1. 
3) If current_max is not 0, then return -1 to ensure that the parenthesis
   are balanced. Else return max

下面是上述算法的实现。

C++

// A C++ program to find the maximum depth of nested
// parenthesis in a given expression
#include 
using namespace std;
 
// function takes a string and returns the
// maximum depth nested parenthesis
int maxDepth(string S)
{
    int current_max = 0; // current count
    int max = 0; // overall maximum count
    int n = S.length();
 
    // Traverse the input string
    for (int i = 0; i < n; i++)
    {
        if (S[i] == '(')
        {
            current_max++;
 
            // update max if required
            if (current_max > max)
                max = current_max;
        }
        else if (S[i] == ')')
        {
            if (current_max > 0)
                current_max--;
            else
                return -1;
        }
    }
 
    // finally check for unbalanced string
    if (current_max != 0)
        return -1;
 
    return max;
}
 
// Driver program
int main()
{
    string s = "( ((X)) (((Y))) )";
    cout << maxDepth(s);
    return 0;
}

Java

//Java program to find the maximum depth of nested
// parenthesis in a given expression
 
class GFG {
// function takes a string and returns the
// maximum depth nested parenthesis
 
    static int maxDepth(String S) {
        int current_max = 0; // current count
        int max = 0; // overall maximum count
        int n = S.length();
 
        // Traverse the input string
        for (int i = 0; i < n; i++) {
            if (S.charAt(i) == '(') {
                current_max++;
 
                // update max if required
                if (current_max > max) {
                    max = current_max;
                }
            } else if (S.charAt(i) == ')') {
                if (current_max > 0) {
                    current_max--;
                } else {
                    return -1;
                }
            }
        }
 
        // finally check for unbalanced string
        if (current_max != 0) {
            return -1;
        }
 
        return max;
    }
 
// Driver program
    public static void main(String[] args) {
        String s = "( ((X)) (((Y))) )";
        System.out.println(maxDepth(s));
    }
}

Python3

# A Python program to find the maximum depth of nested
# parenthesis in a given expression
 
# function takes a string and returns the
# maximum depth nested parenthesis
def maxDepth(S):
    current_max = 0
    max = 0
    n = len(S)
 
    # Traverse the input string
    for i in range(n):
        if S[i] == '(':
            current_max += 1
 
            if current_max > max:
                max = current_max
        else if S[i] == ')':
            if current_max > 0:
                current_max -= 1
            else:
                return -1
 
    # finally check for unbalanced string
    if current_max != 0:
        return -1
 
    return max
 
# Driver program
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
 
# This code is contributed by BHAVYA JAIN

C#

// C# program to find the
// maximum depth of nested
// parenthesis in a given expression
using System;
class GFG {
   
// function takes a string
// and returns the maximum
// depth nested parenthesis
 
static int maxDepth(string S)
{
  // current count
  int current_max = 0;
   
  // overall maximum count
  int max = 0;
   
  int n = S.Length;
 
  // Traverse the input string
  for (int i = 0; i < n; i++)
  {
    if (S[i] == '(')
    {
      current_max++;
 
      // update max if required
      if (current_max > max)
      {
        max = current_max;
      }
    }
    else if (S[i] == ')')
    {
      if (current_max > 0)
      {
        current_max--;
      }
      else
      {
        return -1;
      }
    }
  }
 
  // finally check for unbalanced string
  if (current_max != 0)
  {
    return -1;
  }
 
  return max;
}
 
// Driver program
public static void Main()
{
  string s = "(((X)) (((Y))))";
  Console.Write(maxDepth(s));
}
}
 
// This code is contributed by Chitranayal

PHP

 $max)
                $max = $current_max;
        }
         
        else if ($S[$i] == ')')
        {
            if ($current_max>0)
                $current_max--;
            else
                return -1;
        }
    }
 
    // finally check for
    // unbalanced string
    if ($current_max != 0)
        return -1;
 
    return $max;
}
 
// Driver Code
$s = "( ((X)) (((Y))) )";
echo maxDepth($s);
 
// This code is contributed by mits
?>

Javascript


输出
4

时间复杂度: O(n)
辅助空间: O(1)

?list=PLqM7alHXFySF7Lap-wi5qlaD8OEBx9RMV