We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
题目链接: https://leetcode-cn.com/problems/count-different-palindromic-subsequences
难度: Hard 标签: 字符串 动态规划
Hard
字符串
动态规划
The text was updated successfully, but these errors were encountered:
Difficulty: 困难
Related Topics: 字符串, 动态规划
给定一个字符串 s,返回 s 中不同的非空「回文子序列」个数 。
s
通过从 s 中删除 0 个或多个字符来获得子序列。
如果一个字符序列与它反转后的字符序列一致,那么它是「回文字符序列」。
如果有某个 i , 满足 ai != bi,则两个序列 a1, a2, ... 和 b1, b2, ... 不同。
i
注意:
示例 1:
输入:s = 'bccb' 输出:6 解释:6 个不同的非空回文子字符序列分别为:'b', 'c', 'bb', 'cc', 'bcb', 'bccb'。 注意:'bcb' 虽然出现两次但仅计数一次。
示例 2:
输入:s = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba' 输出:104860361 解释:共有 3104860382 个不同的非空回文子序列,104860361 对 109 + 7 取模后的值。
提示:
1 <= s.length <= 1000
s[i]
'a'
'b'
'c'
'd'
dp
dp(i, i) = 1
j
i + 1
j - 1
s[i] != s[j]
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]
s[i] = s[j]
dp(l, r)
s[l ... r]
2 * dp(i + 1, j - 1)
aa
l = r
+1
l > r
+2
a
l < r
-dp(l + 1, r - 1)
Language: JavaScript
/** * @param {string} s * @return {number} */ var countPalindromicSubsequences = function(s) { const [mod, n] = [1e9 + 7, s.length]; const dp = Array.from({ length: n }, () => new Array(n).fill(0)); for (let i = 0; i < n; i++) dp[i][i] = 1; for (let k = 1; k < n; k++) { for (let i = 0; i < n - k; i++) { let j = i + k; if (s[i] !== s[j]) dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]; else { dp[i][j] = 2 * dp[i + 1][j - 1]; let [l, r] = [i + 1, j - 1]; while (l <= r && s[l] !== s[i]) l++; while (l <= r && s[r] !== s[i]) r--; if (l === r) dp[i][j]++; l > r ? dp[i][j] += 2 : dp[i][j] -= dp[l + 1][r - 1]; } dp[i][j] = (dp[i][j] + mod) % mod; } } return dp[0][n - 1]; };
Sorry, something went wrong.
No branches or pull requests
题目链接: https://leetcode-cn.com/problems/count-different-palindromic-subsequences
难度:
Hard
标签:
字符串
动态规划
The text was updated successfully, but these errors were encountered: