You are given a string ‘STR’, containing only lowercase English letters.
Your task is to determine the total number of distinct substrings present in ‘STR’ which are double strings.
Note :1. A double string is a string that is made by concatenation of some string with itself.
2. The length of a double string is at least 2.
For example :
In the string ‘ababab’, there are just two substrings, that are double strings. Both such substrings are ‘abab’, and thus there exists only one distinct substring which is a double string. ‘abab’ can be written as ‘ab’ + ‘ab’. But ‘ababab’ can not be considered as a double string because ‘ab’ has been concatenated twice with itself.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow.
The first line of each test case contains the string ‘STR’.
Output Format :
For each test case, print a single integer, denoting the total number of distinct substrings which are also double strings.
Output for each test case will be printed in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= |STR| < 2000
Where ‘T’ denotes the number of test cases and |STR| represents the length of the string ‘STR’
Time Limit: 1sec
1
abcarcar
1
In this test case, we can observe that the substring ‘carcar’ can be written as ‘car’ + ‘car’. So, ‘carcar’ is a double substring. Since, this is the only such substring, we print 1.
1
abbasdasda
3
In this case, the substring ‘bb’ can be written as ‘b’ + ‘b’. ‘sdasda’ can be written as ‘sda’ + ‘sda’ and ‘asdasd’ can be written ‘asd’ + ‘asd’. So, a total of 3 substrings exist in the given string which are double strings.
Find out all substrings of even length
Approach:
The approach of this problem is to find out all substrings of even length because for any string to be a double string, it must be of even length. For checking whether a substring is a double string or not, simply check whether all the characters in the first half of the string are equal to the corresponding characters in the second half or not.
Steps:
void isDoubleString(string str) {
O(N^3), where N is the length of the string.
We are finding all substrings in O(N^2) time, and for each substring, we are traversing it entirely to check whether it is a double substring or not. This takes another O(N) time for each substring. So, our overall complexity becomes O(N^3).
O(N), where N is the length of the given string.
We are extra linear space to maintain the set in which all the distinct substrings are getting stored