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

后端 未结 15 1893
你的背包
你的背包 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

    I have to agree the solution may seem to complicated, i think the best solution, to find the largest palindrome in a subsequence, (considering characters in between for example in 'character' the largest palindrome should be carac) is:

    def find_char_backwards(a, c):
    for i in range(len(a) - 1, -1,-1):
        if a[i] == c:
            index=i
            return True, index
    
    return False, 0
    
    def longest_palindorme(a):
    if len(a) < 2:
        return a
    else:
        c=a[0]
        (exist_char,index) = find_char_backwards(a[1:],c)
        if exist_char:
            palindrome=[c] + longest_palindorme(a[1:index+1]) + [c]
        else:
            palindrome=[]
        rest_palidorme=longest_palindorme(a[1:])
    
    if len(palindrome)>len(rest_palidorme):
        return palindrome
    else:
        return rest_palidorme
    

    Where a is an array, this solution uses recursion, and dynamic programming

提交回复
热议问题