-
-
Notifications
You must be signed in to change notification settings - Fork 181
/
longest-palindromic-substring.py
47 lines (42 loc) · 1.16 KB
/
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
# -*- coding:utf-8 -*-
# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
#
# Example 1:
#
#
# Input: "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
#
#
# Example 2:
#
#
# Input: "cbbd"
# Output: "bb"
#
#
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest, mid = "", (len(s) - 1) / 2
i, j = mid, mid
while i >= 0 and j < len(s):
args = [(s, i, i), (s, i, i + 1), (s, j, j), (s, j, j + 1)]
for arg in args:
tmp = self.longestPalindromeByAxis(*arg)
if len(tmp) > len(longest):
longest = tmp
if len(longest) >= i * 2:
if len(longest) == 1:
return s[0]
return longest
i, j = i - 1, j + 1
return longest
def longestPalindromeByAxis(self, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left, right = left - 1, right + 1
return s[left + 1: right]