


The first line of input contains an integer ‘T’, denoting the number of test cases.
The first and only line of each test case contains the string ‘S’.
For each test case, print all distinct palindromic substrings of the given string. Print the substrings in sorted manner and they should be space-separated.
Print the output of each test case in a separate line.
1 <= T <= 10
1 <= |S| <= 1000
String S contains lowercase English letters only.
Where ‘T’ represents the number of test cases and ‘S’ represents the given string.
Time limit: 1 sec
The idea is to simply use three loops and check for each substring if it is palindromic and add it to our output array accordingly. In our implementation, we will be using a Hashmap to keep track of palindromic substrings and will sort all palindromic substrings before returning them.
For each character in the string, consider all odd and even lengths substrings centered at the character. For odd length substrings, keep a string and append the character in the string, compare the left and right characters. If both of them are equal then we can expand that string to left and right as including that left and right character in the string will also result in a palindromic substring. For even length substrings, keep the string empty and expand.
At position I, Each character at J distance to its left and right should be the same to create a palindromic substring of odd length ( S[ I-J ] = S[ I+J ] ).
For example, Consider S = ’abcbd’ and odd length substrings centered at position 3 will be [ ‘c’ , ‘bcb’, ‘abcbd’ ] and palindromic substrings among them are [ ‘c’ , ‘bcb’ ] .
Consider S =’dabbac’ and even length substrings at position 4 will be [ ‘bb’, ‘abba’, ‘dabbac’ ] and palindromic substrings are [ ‘bb’, ‘abba’ ].
Consider S =’abcbd’ and even length substrings centered at position 3 will be [ ‘bc’ , ‘abcb’ ], out of which no substring is palindrome.
We will use a Hashmap to keep track of all palindromic substrings and sort all palindromic substrings before printing.