Longest Common Balanced Substring
Time limit3sMemory limit1024 MB
Given two bracket strings A and B, find the length of the longest string that is a valid bracket sequence and a substring of both, or 0 if none exists.
- Level
Hard8 of 10
- Topics
- String matching, Prefix sum, String
- Solved
- No attempts yet
Problem
Two strings A and B, each made only of ( and ), are given.
Let be the set of distinct strings that are substrings of both A and B and are valid bracket sequences.
Write a program that determines whether has at least one element. If it does, find the length of the longest string in .
You must solve T test cases from one input.
Input
The first line contains the number of test cases T.
Each of the next T lines contains two strings A and B, separated by a single space.
Output
For each test case, print one line in the given order.
- If is empty, print 0.
- Otherwise, print the length of the longest string in .
Constraints
is the total length of all A in one input, and is the total length of all B in one input.
- Each of A and B is a string of length at least 1, made only of opening and closing brackets.
Hints
Valid bracket sequence
A valid bracket sequence is defined as follows.
- The string
()made of one pair of brackets is a valid bracket sequence. - If X is a valid bracket sequence, then
(X)is also a valid bracket sequence. - If X and Y are valid bracket sequences, then their concatenation XY is also a valid bracket sequence.
- Every valid bracket sequence is built only by the three rules above.
For example, (()(())) and (())()() are valid, but (() and )((()() are not.
Substring
For a string s of length l and integers , s[i..j] is the string made of the characters from the i-th through the j-th position of s, in order. Such strings are called substrings of s.
For example, if s is ()(()(), then s[1..5] is (() and s[1..7] is ()(). So (() and ()() are substrings of ()(()(). But )()( is not a substring of ()(()().