-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path005_Longest_Palindromic_Substring.py
48 lines (35 loc) · 1.3 KB
/
005_Longest_Palindromic_Substring.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
https://leetcode.com/problems/longest-palindromic-substring/
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and
there exists one unique longest palindromic substring.
"""
__author__ = 'abhireddy96'
class Solution:
def longestPalindrome(self, s: str) -> str:
# Is string is empty
if not s:
return s
# Contains single character
if len(s) == 1:
return s
# Let first character be resultant palindrome
res = s[0]
# Iterate over string characters
for i in range(0, len(s)):
# Check for Palindrome odd length
cur = self.palindrome_from_center(s, i, i)
if len(cur) > len(res):
res = cur
# Check for Palindrome even length
cur = self.palindrome_from_center(s, i, i + 1)
if len(cur) > len(res):
res = cur
return res
def palindrome_from_center(self, s, begin, end):
while begin >= 0 and end < len(s) and s[begin] == s[end]:
# move pointers outwards
begin -= 1
end += 1
return s[begin + 1: end]
if __name__ == "__main__":
assert Solution().longestPalindrome("dfaaabbbaaac") == "aaabbbaaa"