Guest User

Untitled

a guest
Nov 17th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. # Python3
  2.  
  3. class Solution:
  4. def longestPalindrome(self, s):
  5. """
  6. :type s: str
  7. :rtype: str
  8. """
  9.  
  10. # approach: iterate entire string and expand palindrome
  11.  
  12. start = end = 0
  13. for i in range(len(s)):
  14. candidates = [(start, end)]
  15. candidates.append(self.expandPalindrome(s, i, i))
  16. if i + 1 < len(s) and s[i] == s[i+1]:
  17. candidates.append(self.expandPalindrome(s, i, i + 1))
  18. start, end = max(candidates, key=lambda x: x[1] - x[0])
  19.  
  20. return s[start:end+1]
  21.  
  22. def expandPalindrome(self, s, start, end):
  23. while start > -1 and end < len(s) and s[start] == s[end]:
  24. start -= 1
  25. end += 1
  26.  
  27. return (start + 1, end - 1)
Add Comment
Please, Sign In to add comment