Given a string, print all the possible substrings which are also the prefix of the given string.
Input : ababc Output : a, ab, aba, abab, ababc, a, ab Input : abdabc Output : a, ab, abd, abda, abdab, abdabc, a, ab
We use two variables: start and end to keep track of the current substring and follow the below conditions until
start < len(string):
- If the current substring is also the prefix of the given string, print it and increment end. If
end == len(string), increment start and
end = start
- Else increment start and
end = start
Logic to check if the current substring is a prefix of the given string:
string[end] == string[end-start]
This makes use of the fact that if a substring of length L is a prefix of the given string, then the substring of length L+1 obtained after including the next character ch in the sequence is also a prefix of the given string if the character at (L+1) index in the string is equal to ch.
Below is the implementation of the above approach:
a ab aba abab ababc a ab
- Print the longest prefix of the given string which is also the suffix of the same string
- Python Program to print all permutations of a given string
- Python program to print even length words in a string
- Program to print a doormat pattern having a string written in the center in Python
- Python | Get all substrings of given string
- Python | Get matching substrings in string
- Python | Get the numeric prefix of given string
- Python | Get numeric prefix of given string
- Python Program for Efficient program to print all prime factors of a given number
- Python Program for Program to Print Matrix in Z form
- Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
- Longest string in an array which matches with prefix of the given string
- Python | Print all string combination from given numbers
- Python program to print Emojis
- Print first n distinct permutations of string using itertools in Python
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.