import java.util.Arrays;
class Solution {
private static final int MOD = 1_000_000_007;
public int countPalindromicSubsequences(String s) {
int n = s.length();
int[][] dp = new int[n][n];
// left[c] = first occurrence of character c in the current range [i, ...]
// right[c] = last occurrence of character c in the current range [..., j]
int[] left = new int[4];
int[] right = new int[4];
for (int i = n - 1; i >= 0; i--) {
left[s.charAt(i) - 'a'] = i;
Arrays.fill(right, -1);
for (int j = i; j < n; j++) {
right[s.charAt(j) - 'a'] = j;
// Count palindromic subsequences by their outermost character c.
for (int c = 0; c < 4; c++) {
int l = left[c];
int r = right[c];
if (l == -1 || r == -1) {
continue;
}
if (l == r) {
// Only one occurrence of c: "c"
dp[i][j] = (dp[i][j] + 1) % MOD;
} else if (l + 1 == r) {
// Two adjacent occurrences of c: "c" and "cc"
dp[i][j] = (dp[i][j] + 2) % MOD;
} else {
// Wrap every palindrome inside [l + 1, r - 1] with c,
// plus the two base palindromes "c" and "cc".
dp[i][j] = (dp[i][j] + dp[l + 1][r - 1] + 2) % MOD;
}
}
}
}
return dp[0][n - 1];
}
}
Complexity
· Time: O(n^2) because for each interval we check only 4 possible characters.
· Space: O(n^2) for the DP table.
本文详解LeetCode 730题‘Count Different Palindromic Subsequences’的Java实现,采用动态规划算法,时间复杂度O(n²),空间复杂度O(n²);核心在于按区间DP处理,仅需枚举4种字符(a/b/c/d)边界情况,适用于字符串回文子序列去重计数问题。
215

被折叠的 条评论
为什么被折叠?



