给定的阵列ARR的[] N个字符串,使得每个字符串由字符“(”和“)”中,任务是找到对字符串的最大数目,使得两个字符串的连接是常规支架序列。
A Regular Bracket Sequence is a string consisting of brackets ‘(‘ and ‘)’ such that every prefix from the beginning of the string must have count of ‘(‘ greater than or equal to count of ‘)’ and count of ‘(‘ and ‘)’ are equal in the whole string. For Examples: “(())”, “()((()))”, …, etc
例子:
Input: arr[] = {“) ( ) )”, “)”, “( (“, “( (“, “(“, “)”, “)”}
Output: 2
Explanation:
Following are the pair of strings:
- (2, 1): The string at indices are “((“ and “)())”. Now, the concatenation of these string is “(()())” which is a regular bracket sequence.
- (4, 5): The string at indices are “(“ and “)”. Now, the concatenation of these string is “()” which is a regular bracket sequence.
Therefore, the total count of pairs of regular bracket sequence is 2.
Input: arr[] = {“( ( ) )”, “( )”}
Output: 1
朴素方法:解决给定问题的最简单方法是从给定数组中生成所有可能的字符串对,并计算连接结果为常规括号序列的那些对。检查所有可能的对后,打印获得的总计数。
时间复杂度: O(L*N 2 ),其中 L 是字符串的最大长度。
辅助空间: O(1)
有效的方法:上述方法也可以通过用一对(A, B)描述每个字符串来优化,其中A和B是最小值,这样在将A左括号“(”添加到字符串的左侧和B结束后字符串右边的括号“)”就变成了一个普通的括号序列。为了连接两个括号序列(例如, i th和j th )以产生正确的括号序列,第 i 个序列中左括号的余量必须等于第 j个序列中右括号的余量;即b i = a j 。请按照以下步骤解决问题:
- 初始化两个数组,比如open[]和close[]为0 。此外,将整数变量ans初始化为0 ,以存储对的结果计数。
- 遍历给定数组并执行以下步骤:
- 使用本文讨论的方法,找出需要分别添加到arr[i]左右两侧的左括号和右括号的数量,以使arr[i]成为常规括号序列。设值分别为a和b 。
- 如果a!=0 和 b!=0则arr[i]将需要在其两侧加上括号,因此不可能将其与任何其他字符串。
- 如果a==0 和 b==0则此特定字符串已经是常规括号序列,并且可以与其他常规括号序列的字符串配对。
- 否则,如果a等于0 ,则将close[b]增加1否则将open[a]增加1 。
- 将(close[0]/2)的floor的值与ans的值相加。
- 遍历数组open[]并将open[i]和close[i]的最小值添加到变量ans 。
- 完成以上步骤后,打印ans的值作为结果。
以下是上述方法的实现:-
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to count the number of
// pairs whose concatenation results
// in the regular bracket sequence
static void countPairs(
int N, ArrayList arr)
{
// Stores the count of opening
// and closing parenthesis for
// each string arr[i]
int open[] = new int[100];
int close[] = new int[100];
// Stores maximum count of pairs
int ans = 0;
// Traverse the array arr[]
for (int i = 0; i < N; i++) {
char c[] = arr.get(i).toCharArray();
int d = 0;
int min = 0;
// Traverse the string c[]
for (int j = 0; j < c.length; j++) {
// Opening Bracket
if (c[j] == '(') {
d++;
}
// Otherwise, Closing
// Bracket
else {
d--;
if (d < min)
min = d;
}
}
// Count of closing brackets
// needed to balance string
if (d >= 0) {
if (min == 0)
close[d]++;
}
// Count of opening brackets
// needed to balance string
else if (d < 0) {
if (min == d)
open[-d]++;
}
}
// Add the count of balanced
// sequences
ans += close[0] / 2;
// Traverse the array
for (int i = 1; i < 100; i++) {
ans += Math.min(
open[i], close[i]);
}
// Print the resultant count
System.out.println(ans);
}
// Driver Code
public static void main(String[] args)
{
int N = 7;
ArrayList list = new ArrayList();
list.add(")())");
list.add(")");
list.add("((");
list.add("((");
list.add("(");
list.add(")");
list.add(")");
countPairs(N, list);
}
}
Python3
# Python3 program for the above approach
# Function to count the number of
# pairs whose concatenation results
# in the regular bracket sequence
def countPairs(N, arr):
# Stores the count of opening
# and closing parenthesis for
# each string arr[i]
open = [0] * 100
close = [0] * 100
# Stores maximum count of pairs
ans = 0
# Traverse the array arr[]
for i in range(N):
c = [i for i in arr[i]]
d = 0
minm = 0
# Traverse the string c[]
for j in range(len(c)):
# Opening Bracket
if (c[j] == '('):
d += 1
# Otherwise, Closing
# Bracket
else:
d -= 1
if (d < minm):
minm = d
# Count of closing brackets
# needed to balance string
if (d >= 0):
if (minm == 0):
close[d] += 1
# Count of opening brackets
# needed to balance string
elif (d < 0):
if (minm == d):
open[-d] += 1
# Add the count of balanced
# sequences
ans += close[0] // 2
# Traverse the array
for i in range(1, 100):
ans +=min(open[i], close[i])
# Print the resultant count
print(ans)
# Driver Code
if __name__ == '__main__':
N = 7
list = []
list.append(")())")
list.append(")")
list.append("((")
list.append("((")
list.append("(")
list.append(")")
list.append(")")
countPairs(N, list)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to count the number of
// pairs whose concatenation results
// in the regular bracket sequence
static void countPairs(int N, List arr)
{
// Stores the count of opening
// and closing parenthesis for
// each string arr[i]
int[] open = new int[100];
int[] close = new int[100];
// Stores maximum count of pairs
int ans = 0;
// Traverse the array arr[]
for(int i = 0; i < N; i++)
{
char[] c = arr[i].ToCharArray();
int d = 0;
int min = 0;
// Traverse the string c[]
for(int j = 0; j < c.Length; j++)
{
// Opening Bracket
if (c[j] == '(')
{
d++;
}
// Otherwise, Closing
// Bracket
else
{
d--;
if (d < min)
min = d;
}
}
// Count of closing brackets
// needed to balance string
if (d >= 0)
{
if (min == 0)
close[d]++;
}
// Count of opening brackets
// needed to balance string
else if (d < 0)
{
if (min == d)
open[-d]++;
}
}
// Add the count of balanced
// sequences
ans += close[0] / 2;
// Traverse the array
for(int i = 1; i < 100; i++)
{
ans += Math.Min(open[i], close[i]);
}
// Print the resultant count
Console.WriteLine(ans);
}
// Driver Code
public static void Main(string[] args)
{
int N = 7;
List list = new List();
list.Add(")())");
list.Add(")");
list.Add("((");
list.Add("((");
list.Add("(");
list.Add(")");
list.Add(")");
countPairs(N, list);
}
}
// This code is contributed by ukasp
2
时间复杂度: O(L*N),其中 N 是字符串的最大长度。
辅助空间: O(L)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。