1.NC17 最长回文子串
对于一个字符串,请设计一个高效算法,计算其中最长回文子串的长度。
给定字符串A以及它的长度n,请返回最长回文子串的长度。
输入:"abc1234321ab",12
返回值:7
https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af?tpId=188&&tqId=38608&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking
中间扩散法,遍历数组A,每遍历一个值A[i],就判断左A[i-1]和右A[i+1]的值是否相等,如果相等,再继续判断,直到不等或者i-1==0
目录
或者i+1==n-1.
# -*- coding:utf-8 -*-
class Solution:
def getLongestPalindrome(self, A, n):
# write code here
if n<2:
return n
re = 0
for i in range(n):
if n-i<=re:#未遍历的字符长度不大于re,那么最长的回文肯定不比re长,可以直接退出
break
left = i
right = i
while right<n-1 and A[right+1]==A[right]:#如果遇到相同的字符,right向右移动
right+=1
i = right+1
while left>0 and right<n-1 and A[left-1]==A[right+1]:
left-=1
right+=1
re = max(re,right-left+1)
return re

929

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



