-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path05_LongestPalindromicSubstring.py
executable file
·44 lines (41 loc) · 1.15 KB
/
05_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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: [email protected]
# @Last Modified time: 2016-04-04 17:39:46
class Solution(object):
# Easy to understand. Refer to
# https://leetcode.com/discuss/32204/simple-c-solution-8ms-13-lines
def longestPalindrome(self, s):
if not s:
return ""
s_len = len(s)
if s_len == 1:
return s
max_start, max_end = 0, 1 # Make sure s[start:end] is palindrome
i = 0
while i < s_len:
# No need to check the remainming, pruning here
if max_end - max_start >= (s_len-i) * 2 - 1:
break
left, right = i, i+1
# Skip duplicate characters i.
while right < s_len and s[right-1] == s[right]:
right += 1
i = right
while left-1 >= 0 and right < s_len and s[left-1] == s[right]:
left -= 1
right += 1
if right-left > max_end-max_start:
max_start = left
max_end = right
return s[max_start:max_end]
"""
""
"a"
"aa"
"dcc"
"aaaa"
"cccd"
"ccccdc"
"abcdefead"
"""