Given a string str, the task is to find the longest prefix which is also the suffix of the given string. The prefix and suffix should not overlap. If no such prefix exists then print -1.
Input: str = “aabcdaabc”
The string “aabc” is the longest
prefix which is also suffix.
Input: str = “aaaa”
Approach: The idea is to use pre-processing algorithm of KMP search. In this algorithm, we build lps array which stores the following values:
lps[i] = the longest proper prefix of pat[0..i]
which is also a suffix of pat[0..i].
We get the length using the above approach, then print the same number of characters from the front which is our answer.
Below is the implementation of the above approach:
- String from prefix and suffix of given two strings
- Check if suffix and prefix of a string are palindromes
- Longest prefix which is also suffix
- Find the longest common prefix between two strings after performing swaps on second string
- Python program to print the substrings that are prefix of the given string
- Sub-strings of a string that are prefix of the same string
- Find length of longest subsequence of one string which is substring of another string
- Check if a string is suffix of another
- Count of distinct substrings of a string using Suffix Trie
- Count of distinct substrings of a string using Suffix Array
- Maximum length prefix of one string that occurs as subsequence in another
- Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated
- Length of Longest sub-string that can be removed
- Longest double string from a Palindrome
- Print shortest path to print a string on screen
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : prerna saini