第九章 动态规划part17

69 阅读1分钟

647. Palindromic Substrings

Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward.

substring is a contiguous sequence of characters within the string.

题目解析:

  • 根据回文串的性质,可以从中间往两边扩展,中间有两种情况:
    • 中间只有一个元素
    • 中间为两个元素

代码:

class Solution {
    public int countSubstrings(String s) {
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            num += numOfPalindrom(s, i, i);
            num += numOfPalindrom(s, i-1, i);
        }
        return num;
    }

    public int numOfPalindrom(String s, int left, int right) {
        int count = 0;
        while (left >= 0 && right < s.length()) {
            if (s.charAt(left--) == s.charAt(right++)) {
                count++;
            } else {
                break;
            }
        }
        return count;
    }
}

516. Longest Palindromic Subsequence

Given a string s, find the longest palindromic subsequence's length in s.

subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

题目解析:

  • dp[i][j] 依赖于 dp[i + 1][j - 1] ,dp[i + 1][j] 和 dp[i][j - 1]
  • 遍历顺序:从下往上,从左往右

代码:

class Solution {
    public int longestPalindromeSubseq(String s) {
        int[][] dp = new int[s.length() + 1][s.length() + 1];
        for (int i = s.length() - 1; i >= 0; i--) {
            dp[i][i] = 1;
            for (int j = i+1; j < s.length(); j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i+1][j-1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
                }
            }
        }
        return dp[0][s.length() - 1];
    }
}