'How to get list of palindrome in text? [closed]

I have the following interview question that may require traversing through the entire string.

  • Problem I searched about find Problem and most people do it like this def palindrome(s): return s==s[::-1] But this task is diffrent?

  • palindrome is a word the can read from both directions like 'mam', 'dad'. Your task is to get a list of palindrome in a given string.

def palindrome(s):

  stack = []
  return ['aaa']

exampls

palindrome('aaa') #['aaa']
palindrome('abcbaaaa') #['abcba','aaaa']
palindrome('xrlgabccbaxrlg') #['abccba']
palindrome('abcde') #['']



Solution 1:[1]

Let's try to avoid checking all the possible combinations :). My idea is, start from the extremities and converge:

def palindrome(s):
    out = [''] #we need the list to not be empty for the following check
    for main_start in range(len(s) - 1):
        for main_end in range(len(s) - 1, main_start, -1):
            start = main_start
            end = main_end
            while (end - start) > 0:
                if s[start] == s[end]: ##may be palindrome
                    start += 1
                    end -= 1
                else:
                    break
            else:
                if s[main_start:main_end + 1] not in out[-1]: #ignore shorter ("inner") findings
                    out.append(s[main_start:main_end + 1])
    return out[1:] #skip the dummy item

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gimix