LeetCode刷题 Day57

50 阅读1分钟

LeetCode刷题 Day57

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.

Example 1:

Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

思路: 相等要考虑到三种情况:

  1. i === j相等
  2. Math.abs(i - j) === 1,[i] === s[j]
  3. Math.abs(i - j) > 1, s[i] === s[j], 且dp[i + 1][j - 1] is true

代码:

var countSubstrings = function(s) {
    const len = s.length;
    let numOfPalindromicStr = 0;
    let dp = Array.from(Array(len), () => Array(len).fill(false));

    for(let i = len - 1; i >= 0; i--) {
        for(let j = i; j < len; j++) {
            if(s[i] === s[j]) {
                if((j - i) < 2) {
                    dp[i][j] = true;
                } else {
                    dp[i][j] = dp[i+1][j-1];
                }
                numOfPalindromicStr += dp[i][j] ? 1 : 0;
            }
        }
    }

    return numOfPalindromicStr;
};

时间复杂度: O(mn) 空间复杂度: O(mn)


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.

 Example 1:

Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".

Example 2:

Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".
var longestPalindromeSubseq = function(s) {
    const len = s.length;
    let dp = Array(len).fill(0).map(() => Array(len).fill(0));

    for (let i = 0; i < len; i++) dp[i][i] = 1;
    for (let i = len - 1; i >= 0; i--) {
        for (let j = i + 1; j < len; j++) {
            if (s[i] === s[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][len - 1];
};