|
| 1 | +/** |
| 2 | + * 730. Count Different Palindromic Subsequences |
| 3 | + * https://leetcode.com/problems/count-different-palindromic-subsequences/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a string s, return the number of different non-empty palindromic subsequences in s. |
| 7 | + * Since the answer may be very large, return it modulo 109 + 7. |
| 8 | + * |
| 9 | + * A subsequence of a string is obtained by deleting zero or more characters from the string. |
| 10 | + * |
| 11 | + * A sequence is palindromic if it is equal to the sequence reversed. |
| 12 | + * |
| 13 | + * Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {string} s |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +var countPalindromicSubsequences = function(s) { |
| 21 | + const MOD = 1e9 + 7; |
| 22 | + const dp = new Array(s.length).fill().map(() => { |
| 23 | + return new Array(s.length).fill(0); |
| 24 | + }); |
| 25 | + |
| 26 | + for (let i = 0; i < s.length; i++) { |
| 27 | + dp[i][i] = 1; |
| 28 | + } |
| 29 | + |
| 30 | + for (let len = 2; len <= s.length; len++) { |
| 31 | + for (let start = 0; start + len <= s.length; start++) { |
| 32 | + const end = start + len - 1; |
| 33 | + const charStart = s[start]; |
| 34 | + const charEnd = s[end]; |
| 35 | + |
| 36 | + if (charStart !== charEnd) { |
| 37 | + dp[start][end] = (dp[start + 1][end] + dp[start][end - 1] - dp[start + 1][end - 1]) % MOD; |
| 38 | + } else { |
| 39 | + let left = start + 1; |
| 40 | + let right = end - 1; |
| 41 | + |
| 42 | + while (left <= right && s[left] !== charStart) left++; |
| 43 | + while (left <= right && s[right] !== charStart) right--; |
| 44 | + |
| 45 | + if (left > right) { |
| 46 | + dp[start][end] = (2 * dp[start + 1][end - 1] + 2) % MOD; |
| 47 | + } else if (left === right) { |
| 48 | + dp[start][end] = (2 * dp[start + 1][end - 1] + 1) % MOD; |
| 49 | + } else { |
| 50 | + dp[start][end] = (2 * dp[start + 1][end - 1] - dp[left + 1][right - 1]) % MOD; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if (dp[start][end] < 0) dp[start][end] += MOD; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return dp[0][s.length - 1]; |
| 59 | +}; |
0 commit comments