Given a string "ababacba"
, how can I generate all possible palindrome substrings?
I was thinking of an approach of the following:
However, it seems that this might not work for certain cases such as it detects baba
as a palindrome when it is not, because reading ababacba is the same as reading ababacba, both bolded statement have abab
and its reversed baba
.
Hence, I think this approach is not valid, so how can I generate all palindrome substrings using a trie?
Desired output for string ababacba
:
ababa
bab
aba
Thank you.
First find all substrings and then check if they are palindrome. This methods probably doesn't work that fast for very long strings.
def substrings(string, n):
result = []
for i in range(len(string)-n+1):
result.append(string[i:i+n])
return result
def all_substrings(string, min_n=2):
result = []
for n in range(min_n, len(string)):
result+=substrings(string, n)
return result
def is_palindrom(string):
return string == string[::-1] #[::-1] reverses string (look for slicing)
def sub_palindroms(string, min_n=2):
return [s for s in all_substrings(string, min_n=min_n) if is_palindrom(s)]
print(sub_palindroms('ababacba'))