Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. class Solution:
  2. def longestPalindrome(self, s: str) -> str:
  3. longestSubstring = ""
  4. substring = ""
  5. stringLength = len(s)
  6. if self.isPalindrome(s, stringLength):
  7. return s
  8. endIndex = stringLength + 1
  9. for i in reversed(range(endIndex)):
  10. for j in range(i):
  11. substringLength = i - j
  12. if len(longestSubstring) < substringLength:
  13. substring = s[j:i]
  14. if self.isPalindrome(substring, substringLength):
  15. longestSubstring = substring
  16.  
  17. return longestSubstring
  18.  
  19. def isPalindrome(self, s: str, stringLength: int) -> bool:
  20. """Takes a string and returns True if the string is a palindrome
  21. Arguments:
  22. s {str} -- The string to be tested
  23. stringLength {int} -- The length of the string
  24. Returns:
  25. bool -- True if it's a palindrome, False if it's not
  26. """
  27.  
  28. if stringLength < 2:
  29. return True
  30.  
  31. midpoint = stringLength // 2
  32. if stringLength % 2 != 0:
  33. # It's odd, so the midpoint doesn't matter
  34. if s[:midpoint] == s[:midpoint:-1]:
  35. return True
  36. return False
  37. else:
  38. # It's even
  39. if s[:midpoint] == s[: midpoint - 1 : -1]:
  40. return True
  41. return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement