Skip to content

Commit e1eeff9

Browse files
committedJun 19, 2018
Longest Palindrom substring solution in space O(1)
1 parent 95edd69 commit e1eeff9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
 

‎1-100q/05.py

+24
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,27 @@ def longestPalindrome(self, s):
4848

4949
# Space: O(N^2)
5050
# Time: O(N^2)
51+
52+
class Solution(object):
53+
def longestPalindrome(self, s):
54+
"""
55+
:type s: str
56+
:rtype: str
57+
"""
58+
59+
def expand(s, left, right):
60+
while left >= 0 and right < len(s) and s[left] == s[right]:
61+
left -= 1
62+
right += 1
63+
return right-left-1
64+
65+
start, end = 0, 0
66+
for index in range(len(s)):
67+
even_len = expand(s, index, index+1)
68+
odd_len = expand(s, index, index)
69+
length = max(even_len, odd_len)
70+
if length > (end-start):
71+
start = index - (length-1)/2
72+
end = index +length/2
73+
74+
return s[start:end+1]

0 commit comments

Comments
 (0)
Please sign in to comment.