题目来源:

https://leetcode-cn.com/problems/longest-palindromic-subsequence/

题目描述:

LeetCode516.最长回文子序列

代码如下:

class Solution {
    public int longestPalindromeSubseq(String s) {
        if (s == null || s.length() == 0) return 0;
        if(s.length()==1) return 1;

        char[] chars = s.toCharArray();
        if(s.length()==2) return chars[0] == chars[1] ? 2 : 1;

        //三个字符才开始循环判断
        int[][] array = new int[s.length()][s.length()];
        for (int i = 0; i < s.length(); i++) {
            array[i][i] = 1;
            for (int j = i-1; j >-1 ; j--) {
                if(chars[j]==chars[i]){
                    array[i][j] = 2 + array[i - 1][j + 1];
                }else {
                    array[i][j] = Math.max(array[i-1][j],array[i][j+1]);
                }
            }
        }
        return array[chars.length-1][0];

    }
}

 

相关文章:

  • 2022-12-23
  • 2022-01-24
  • 2022-12-23
  • 2022-02-28
  • 2021-10-24
  • 2021-06-25
  • 2022-02-26
  • 2021-08-05
猜你喜欢
  • 2021-09-03
  • 2022-12-23
  • 2022-12-23
  • 2021-06-06
  • 2021-06-19
  • 2021-08-21
  • 2022-02-20
相关资源
相似解决方案