Perfect reversible string
You are given a string ‘str’, the task is to check that reverses of all possible substrings of ‘str’ are present in ‘str’ or not.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : str = "ab" Output: "NO" // all substrings are "a","b","ab" but reverse // of "ab" is not present in str Input : str = "aba" Output: "YES" Input : str = "abab" Output: "NO" // All substrings are "a", "b", "a", "b", "ab", // "ba", "ab", "aba", "bab", "abab" but reverse of // "abab" is not present in str
A simple solution for this problem is to generate all possible substrings of ‘st’ and check if their reverse exist in the ‘str’ linearly.
An efficient solution for this problem is based on the fact that reverse of all substrings of ‘str’ will exist in ‘str’ if and only if the entire string ‘str’ is palindrome. We can justify this fact by considering the whole string, a reverse of it will exist only if it is palindrome. And if a string is palindrome, then all reverse of all substrings exist.
Below is implementation of above idea.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.