0

Given a string "ababacba", how can I generate all possible palindrome substrings?

I was thinking of an approach of the following:

  1. Generate a suffix trie with the original string
  2. Reverse the string
  3. Generate all suffixes of the reversed string
  4. For each of this suffixes, compare by going each node in the suffix trie to determine palindrome

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.

alphawolf
  • 13
  • 5
  • Do you have to ***generate*** or to ***find*** the palindrome substrings? – Sterconium Oct 03 '19 at 15:56
  • What's the difference between **_generate_** and **_find_**? I want to find those palindrome substrings. – alphawolf Oct 03 '19 at 16:08
  • Generate means to create something new; find means to look for what's already there. Why do you want to use a trie for that? – M Oehm Oct 03 '19 at 17:26
  • @MOehm I am trying to complete a challenge assigned by my tutor. – alphawolf Oct 03 '19 at 17:58
  • The problem with palindromes is that the starting point for the forwards and backwards traversal must be identical or adjacent positions. I don't see how a trie helps with that. – M Oehm Oct 03 '19 at 18:57
  • @MOehm it’s possible to use a trie. But I’m not sure how. – alphawolf Oct 04 '19 at 02:25
  • Sure, it's possible, but is it reasonable? (There is an interview question where you have to find palindrome pairs from a dictionary, e.g. "trap" and "part". There, you can create forward and backwards tries and walk them simultaneously, thereby reducing the serch space greatly, because otherwise you'd have to check all word pairs or at least reverse all words and look them up in a hashtable. In your problem, nothing is gained by using a trie. Your best bet is probably to use each letter or letter "twin" and walk both left and right as long as the letters match.) – M Oehm Oct 04 '19 at 05:41

1 Answers1

0

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'))
Flostian
  • 93
  • 1
  • 7