可惜没如果=_=
时光的河入海流

题目链接在这里:5. 最长回文子串 - 力扣(LeetCode)

首先肯定是个n^2的算法,枚举起点也是必要的,但是枚举终点很显然不行,但是考虑到回文串会向下兼容,因此我们可以枚举长度,这就是典型的区间dp了,从短的子串可以推到长的子串的信息的可以用区间dp做。

 

 1 class solution:
 2     def longest(self,s : str)->str:
 3         ans = 0
 4         lft = rgt = 0
 5         n = len(s)
 6         f=[[False] * n for _ in range(n)]
 7         ans = 1
 8         for i in range(n):
 9             f[i][i] = True
10         for i in range(n-1):
11             if s[i] == s[i+1] :
12                 f[i][i+1] = True
13                 ans = 2
14                 lft = i
15             else:
16                 f[i][i+1] = False
17         for length in range(3, n+1):
18             for i in range(n-length+1):
19                 j = i+length - 1 
20                 # print(i,j)
21                 if s[i] == s[j]:
22                     f[i][j]=f[i+1][j-1]
23                 if f[i][j]==True:
24                     ans = length
25                     lft = i
26         return s[lft: lft+ans]
27 
28 if __name__=="__main__":
29     s = "ccc"
30     an = solution.longest(self=0,s=s)
31     print(an)

 

posted on 2023-03-18 22:37  珍珠鸟  阅读(15)  评论(0编辑  收藏  举报