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:
- Find the longest sub-string which is prefix, suffix and also present inside the string
- Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
- String from prefix and suffix of given two strings
- Longest string in an array which matches with prefix of the given string
- Check if suffix and prefix of a string are palindromes
- Longest prefix which is also suffix
- Longest prefix in a string with highest frequency
- 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
- Longest sub string of 0's in a binary string which is repeated K times
- Check if a string is suffix of another
- Count of distinct substrings of a string using Suffix Array
- Count of distinct substrings of a string using Suffix Trie
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.