Advertisement
makispaiktis

DCP46 - Longest palindrome substring

Oct 15th, 2020 (edited)
2,795
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. '''
  2. This problem was asked by Amazon.
  3. Given a string, find the longest palindromic contiguous substring. If there are more than one with the maximum length, return any one.
  4. For example, the longest palindromic substring of "aabcdcb" is "bcdcb". The longest palindromic substring of "bananas" is "anana".
  5. '''
  6.  
  7. # 1st Function
  8. def isPalindrome(word):
  9.     n = len(word)
  10.     if n == 1:
  11.         # A word with 1 letter cannot be a palindrome
  12.         return False
  13.     flag = True
  14.     for i in range(int(n/2)):
  15.         if word[i] != word[n - 1 - i]:
  16.              flag = False
  17.              break
  18.     return flag
  19.  
  20. # 2nd Function
  21. def longestPalindrome(messageWord):
  22.     n = len(messageWord)
  23.     flag = False
  24.     if isPalindrome(messageWord):
  25.         flag = True
  26.         return messageWord
  27.     # Now, I will search for "consecutive" substrings that are maybe palindromes
  28.     for LENGTH in range(n-1, 0, -1):
  29.         # We speak about substrings with length = LENGTH
  30.         # If my word has 7 letters, I look 2 substrings with LENGTH = 6, 3 substrings with LENGTH = 5 etc
  31.         for firstIndex in range(0, n+1 - LENGTH):
  32.             word = messageWord[firstIndex : firstIndex+LENGTH]
  33.             if isPalindrome(word):
  34.                 flag = True
  35.                 return word
  36.     if flag == False:
  37.         return ("The word '" + str(messageWord) + "' does not contain any palindrome")
  38.  
  39.  
  40. # 3rd Function
  41. def prettyPrint(messageWord):
  42.     answer = longestPalindrome(messageWord)
  43.     print(str(messageWord) + " ----> longest palindrome substring = " + str(answer))
  44.  
  45. # MAIN FUNCTION
  46. messageWords = ["bananas", "banana", "anana", "Anana", "Saab", "aara", "BB", "cb", "c"]
  47. for messageWord in messageWords:
  48.     prettyPrint(messageWord)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement