2484. Count Palindromic Subsequences
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.
Example 1:
Input: s = "103301" Output: 2 Explanation: There are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301". Two of them (both equal to "10301") are palindromic.
Example 2:
Input: s = "0000000" Output: 21 Explanation: All 21 subsequences are "00000", which is palindromic.
Example 3:
Input: s = "9999900000" Output: 2 Explanation: The only two palindromic subsequences are "99999" and "00000".
Constraints:
1 <= s.length <= 104
s
consists of digits.
class Solution { public int countPalindromes(String s) { // 计算左侧的两位排列个数 int[][][] l2r = countLeftToRight(s); // 计算右侧的两位排列个数 int[][][] r2l = countRightToLeft(s); int MOD = 1000_000_007; long result = 0; // 从第3个元素开始,计算左右侧100中情况的count,相加 for(int i = 2; i < s.length() - 2; i++) { for(int j = 0; j < 10; j++) { for(int k = 0; k < 10; k++) { result += 1l * l2r[i - 1][j][k] * r2l[i + 1][j][k]; result = result % MOD; } } } return (int)result; } private int[][][] countLeftToRight (String s) { // 记录当前某数字出现的次数 int[] cnt = new int[10]; int[][][] count = new int[s.length()][10][10]; // i为当前第二个数字的位置 for(int i = 0; i < s.length(); i++) { int c = s.charAt(i) - '0'; if(i > 0) { // j 为第一个数字 0~9 for(int j = 0; j < 10; j++) { // k 为第二个数字 0~9 for(int k = 0; k < 10; k++) { count[i][j][k] = count[i - 1][j][k]; // 如果k是当前数字,那么当前的count要加上 if(c == k) count[i][j][k] += cnt[j]; } } } cnt[c]++; } return count; } private int[][][] countRightToLeft (String s) { // 记录当前某数字出现的次数 int[] cnt = new int[10]; int[][][] count = new int[s.length()][10][10]; for(int i = s.length() - 1; i >= 0; i--) { int c = s.charAt(i) - '0'; if(i < s.length() - 1) { for(int j = 0; j < 10; j++) { for(int k = 0; k < 10; k++) { count[i][j][k] = count[i + 1][j][k]; if(c == k) count[i][j][k] += cnt[j]; } } } cnt[c]++; } return count; } }
标签:count,10,cnt,题目,int,未分类,++,length,dp From: https://www.cnblogs.com/cynrjy/p/18018716