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.
题目来自: https://oj.leetcode.com/problems/longest-palindromic-substring/
这一题是求一个字符串(长度<=1000)中最长的回文子串(题目限定只有唯一一个)。难度标注为"Medium"
我想这题也比较简单,思路就是完整扫描,遇到有回文可能的位置开始左右观察。记录最大值。
class Solution:
# @return a string
def longestPalindrome(self, s):
lenstr = len(s)
maxlen = 1
maxstart, maxend = 0, 0
#向左向右比较确定是否回文
def scancmp(s, start, end):
while ((start - 1 >= 0) and (end + 1 <= lenstr - 1)):
if s[start - 1] != s[end + 1]:
break
start -= 1
end += 1
return start, end
for i in range(1, lenstr):
#回文形式'aba'
if (i < lenstr - 1) and s[i + 1] == s[i - 1]:
start, end = scancmp(s, i - 1, i + 1)
if (end + 1 - start) > maxlen:
maxlen, maxstart, maxend = (end + 1 -start), start, end
#回文形式'aa'
if s[i] == s[i - 1]:
start, end = scancmp(s, i - 1, i)
if (end + 1 - start) > maxlen:
maxlen, maxstart, maxend = (end + 1 -start), start, end
return s[maxstart:maxend + 1]

817

被折叠的 条评论
为什么被折叠?



