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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.