如何获取文本中的回文列表?

How to get list of palindrome in text?

我有以下面试题,可能需要遍历整个字符串。

def palindrome(s):

  stack = []
  return ['aaa']

例子

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

让我们尽量避免检查所有可能的组合:)。我的想法是,从四肢着手,收敛:

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