How to find longest palindrome substring in Python

2 Answers

0 votes
def longestPalindromeSubstring(str) :
    size = len(str)
    longestLength = 1
    start = 0
    i = 0
    while (i < size) :
        j = i
        while (j < size) :
            palindrome = 1
            k = 0
            while (k < int((j - i + 1) / 2)) :
                if (str[i + k] != str[j - k]) :
                    palindrome = 0
                k += 1
                
                if (palindrome != 0 and (j - i + 1) > longestLength) :
                    start = i
                    longestLength = j - i + 1
            j += 1
        i += 1
    
    print("Longest palindrome substring = ", end ="")
    i = start
    while (i <= start + longestLength - 1) :
        print(str[i], end ="")
        i += 1
    print("\n", end ="")
    
    return longestLength

s = "qabcbaproggorpxyyxzv"
result = longestPalindromeSubstring(s)
print("Length palindrome substring length = " + str(result))



'''
run:

Longest palindrome substring = proggorp
Length palindrome substring length = 8

'''

 



answered Jun 3, 2023 by avibootz
0 votes
def longestPalindromeSubstring(str) :
    longestpalindrome = ''
    size = len(s)
    
    for i in range(size):
        for j in range(i + 1, size + 1):
            word = s[i:j]
            if word == word[::-1]:
                if len(word) > len(longestpalindrome):
                    longestpalindrome = word   
                    
    return longestpalindrome
    
s = "qabcbaproggorpxyyxzv"
result = longestPalindromeSubstring(s)

print("Longest palindrome substring = " + result)
print("Length palindrome substring length = " + str(len(result)))



'''
run:

Longest palindrome substring = proggorp
Length palindrome substring length = 8

'''

 



answered Jun 3, 2023 by avibootz

Related questions

1 answer 130 views
1 answer 132 views
2 answers 173 views
1 answer 118 views
1 answer 123 views
...