-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2484-count-palindromic-subsequences.js
More file actions
59 lines (53 loc) · 1.75 KB
/
2484-count-palindromic-subsequences.js
File metadata and controls
59 lines (53 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 2484. Count Palindromic Subsequences
* https://leetcode.com/problems/count-palindromic-subsequences/
* Difficulty: Hard
*
* Given a string of digits s, return the number of palindromic subsequences of s having length 5.
* Since the answer may be very large, return it modulo 109 + 7.
*
* Note:
* - A string is palindromic if it reads the same forward and backward.
* - A subsequence is a string that can be derived from another string by deleting some or no
* characters without changing the order of the remaining characters.
*/
/**
* @param {string} s
* @return {number}
*/
var countPalindromes = function(s) {
const MOD = 1e9 + 7;
const n = s.length;
const prefixPairs = new Array(n).fill(0).map(() => new Array(100).fill(0));
const suffixPairs = new Array(n).fill(0).map(() => new Array(100).fill(0));
for (let i = 1; i < n; i++) {
for (let pair = 0; pair < 100; pair++) {
prefixPairs[i][pair] = prefixPairs[i - 1][pair];
}
for (let j = 0; j < i; j++) {
const pair = parseInt(s[j]) * 10 + parseInt(s[i]);
prefixPairs[i][pair]++;
}
}
for (let i = n - 2; i >= 0; i--) {
for (let pair = 0; pair < 100; pair++) {
suffixPairs[i][pair] = suffixPairs[i + 1][pair];
}
for (let j = i + 1; j < n; j++) {
const pair = parseInt(s[i]) * 10 + parseInt(s[j]);
suffixPairs[i][pair]++;
}
}
let result = 0;
for (let i = 2; i < n - 2; i++) {
for (let first = 0; first < 10; first++) {
for (let second = 0; second < 10; second++) {
const leftPair = first * 10 + second;
const rightPair = second * 10 + first;
result = (result + (prefixPairs[i - 1][leftPair]
* suffixPairs[i + 1][rightPair]) % MOD) % MOD;
}
}
}
return result;
};