Skip to content

Commit 426ba0a

Browse files
authored
Create 730-count-different-palindromic-subsequences.js
1 parent fd42583 commit 426ba0a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string} S
3+
* @return {number}
4+
*/
5+
const countPalindromicSubsequences = function(S) {
6+
const len = S.length
7+
const dp = Array.from({ length: len }, () => new Array(len).fill(0))
8+
const mod = 10 ** 9 + 7
9+
for (let i = 0; i < len; i++) dp[i][i] = 1
10+
for (let distance = 1; distance < len; distance++) {
11+
for (let i = 0; i < len - distance; i++) {
12+
let j = i + distance
13+
if (S[i] === S[j]) {
14+
let low = i + 1
15+
let high = j - 1
16+
while (low <= high && S[low] != S[j]) low++
17+
while (low <= high && S[high] != S[j]) high--
18+
if (low > high) {
19+
dp[i][j] = dp[i + 1][j - 1] * 2 + 2
20+
} else if (low == high) {
21+
dp[i][j] = dp[i + 1][j - 1] * 2 + 1
22+
} else {
23+
dp[i][j] = dp[i + 1][j - 1] * 2 - dp[low + 1][high - 1]
24+
}
25+
} else {
26+
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]
27+
}
28+
dp[i][j] = dp[i][j] < 0 ? dp[i][j] + mod : dp[i][j] % mod
29+
}
30+
}
31+
return dp[0][len - 1]
32+
}

0 commit comments

Comments
 (0)