-
Notifications
You must be signed in to change notification settings - Fork 20
/
LongestPalindromicSubstring.py
58 lines (52 loc) · 1.47 KB
/
LongestPalindromicSubstring.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
49
50
51
52
53
54
55
56
57
58
# -*- 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:
#
# Input: "babad"
#
# Output: "bab"
#
# Note: "aba" is also a valid answer.
# Example:
#
# Input: "cbbd"
#
# Output: "bb"
#
# Python, Python3 all accepted.
class LongestPalindromicSubstring:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if s is None:
return s
length = len(s)
if length <= 1:
return s
max_length = 0
start_index = 0
for index in range(length):
leftIndex = index
rightIndex = index
while leftIndex >= 0 and rightIndex < length and s[leftIndex] == s[rightIndex]:
current = rightIndex - leftIndex + 1
if current > max_length:
max_length = current
start_index = leftIndex
leftIndex -= 1
rightIndex += 1
leftIndex = index
rightIndex = index + 1
while leftIndex >= 0 and rightIndex < length and s[leftIndex] == s[rightIndex]:
current = rightIndex - leftIndex + 1
if current > max_length:
max_length = current
start_index = leftIndex
leftIndex -= 1
rightIndex += 1
return str(s[start_index: start_index + max_length])