DeepSeek LeetCode 730. Count Different Palindromic Subsequences Java Implement

本文详解LeetCode 730题‘Count Different Palindromic Subsequences’的Java实现,采用动态规划算法,时间复杂度O(n²),空间复杂度O(n²);核心在于按区间DP处理,仅需枚举4种字符(a/b/c/d)边界情况,适用于字符串回文子序列去重计数问题。
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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址