Python: search longest palindromes within a word and palindromes within a word/string

后端 未结 15 1833
你的背包
你的背包 2020-12-03 09:38

So here is a code i have written to find palindromes within a word (To check if there are palindromes within a word including the word itself) Condition: spaces inbetween ch

15条回答
  •  独厮守ぢ
    2020-12-03 10:00

    Here is another clean and simple approach taken from the excellent online course Design of Computer Programs by P. Norvig. It iterates over all characters in the string and attempts to "grow" the string to both left and right.

    def longest_sub_palindrome_slice(text):
        "Return (i,j) such that text[i,j] is the longest palindrome in text"
        if text == '': return (0, 0)
        def length(slice): a,b = slice; return b-a
        candidates = [grow(text, start, end)
                     for start in range(len(text))
                     for end in (start, start + 1)]
        return max(candidates, key=length)
    
    def grow(text, start, end):
        "Start with a 0- or 1- length palindrome; try to grow a bigger one"
        while (start > 0 and end < len(text)
               and text[start-1].upper() == text[end].upper()):
            start -= 1; end += 1
        return (start, end)
    

提交回复
热议问题