from icecream import ic ics logestsubstr 申请长度为n的列表 并初始化 同上 当 j 时 第 i 个子串为回文子串 判断长度 当j i 1时 判断s i 是否等于s j 并判断当j 1时 第i 1个子串是否为回文子串 当 j 时 第 i 个子串为回文子串 覆盖旧的列表 新的列表清空 from icecream import ic ic s logestsubstr logestsubstr
def longest_palindromic_subsequence(s):

    k = len(s)
    olist = [0] * k    
    nList = [0] * k    
    logestSubStr = ""
    logestLen = 0

    for j in range(0, k):
        for i in range(0, j + 1):
            if j - i <= 1:
                if s[i] == s[j]:
                    nList[i] = 1                 
                    len_t = j - i + 1
                    if logestLen < len_t:        
                        logestSubStr = s[i:j + 1]
                        logestLen = len_t
            else:
                if s[i] == s[j] and olist[i+1]:   
                    nList[i] = 1                  
                    len_t = j - i + 1
                    if logestLen < len_t:
                        logestSubStr = s[i:j + 1]
                        logestLen = len_t
        olist = nList                            
        nList = [0] * k                          
    
    
    return logestLen