Leetcode #5. Longest Palindromic Substring

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode #5. Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。

Q: 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. 
 
1. For each element in the array, use it as center to expand until it is not palindromic. 
2. Use two pointers to locate the start and end of the palindromic substring.
3. Pay attention to the odd and even case 

 1 class Solution(object):
 2     def longestPalindrome(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         abccba abcba
 7         """
 8 
 9         n = len(s)
10         start = end = 0
11         for i in range(n):
12             len1 = self.range(s, i, i)
13             len2 = self.range(s, i, i + 1)
14             maxLen = max(len1, len2)
15 
16             if maxLen > end - start:
17                 end = i + (maxLen) / 2
18                 start = i - (maxLen - 1) / 2
19 
20         return s[start:end + 1]
21 
22     def range(self, s, l, r):
23         while l >= 0 and r < len(s) and s[l] == s[r]:
24             l -= 1
25             r += 1
26         return r - l - 1

 



以上是关于Leetcode #5. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring

LeetCode题解 #5 Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

Leetcode #5. Longest Palindromic Substring

LeetCode 5_Longest Palindromic Substring