程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

leetcode 算法题(5) python解法

hfteth 2025-05-28 17:21:58 技术文章 3 ℃

后面会继续写有关wifi的内容,最近继续算法练习

题目: 给定一个字符串 s,找到 s 中最长的回文子串。可以假设 s 的最大长度为 1000。

思路:根据回文特性,可以暴力计算但比较耗时。这里根据leetcode其他人介绍的中心检测法,来实现。即因为回文左右对称,即有中心点。遍历中心点,即可用n^2的时间复杂度求解。

代码:

 res = ''
 if s is None or len(s)< 1:
 return res
 for i in range(0,len(s)):
 s1 = self.pointAroud(s,i,i)
 s2 = self.pointAroud(s,i,i+1)
 if len(s1) > len(s2):
 if len(s1) > len(res):
 res = s1
 else:
 if len(s2) > len(res):
 res = s2
 return res
 def pointAroud(self,s,left,right):
 while left > -1 and right < len(s) and s[left] == s[right]:
 left -= 1
 right += 1
 return s[left+1:right]

结果:

Tags:

最近发表
标签列表