Leetcode516: Longest Palindromic Subsequence
具体题目如下:
Given a string s, find the longest palindromic subsequence’s length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
“bbbab”
Output:
4
One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input:
“cbbd”
Output:
2
One possible longest palindromic subsequence is “bb”.
思路:以原字符串s的每个字符为基准,向前遍历字符,如果前面的字符与当前字符相同,则回文子序列的大小在除去这两个字符的子序列的基础上加2,则p[i][j] = p[i-1][j+1] + 2,其中p[i][j]表示s中第i个字符到第j个字符的回文子序列长度(i>=j);如果前面的字符与当前字符不相同,则回文子序列的大小为除去其中一个字符的子序列的最大值,则p[i][j] = max(p[i-1][j],p[i][j+1]);找到该递推关系后,做遍历即可,时间复杂度为O(n^2).
class Solution:
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
slen = len(s)
if s==s[::-1]:
return slen
p = [[1 for i in range(slen)] for j in range(slen)]
for i in range(slen):
if s[i]==s[i-1]:
p[i][i-1] = 2
for j in range(i-2,-1,-1):
if s[j]==s[i]:
p[i][j] = p[i-1][j+1] + 2
else:
p[i][j] = max(p[i-1][j],p[i][j+1])
return p[slen-1][0]