题目描述:

image-20250119221359222

解析:动态规划,dp用于存储到当前位置为止的消息数量,循环遍历数组,如果跟前一个字符相同,累加,如果在跟前两个位置的字符相同,再累加,如果是7或9,并且跟前三个字符相同,再累加。

package January;

/**
* @author hxw
* @version 1.0
* @date 2025/1/19 22:02
* @description: 2266. 统计打字方案数 中等
*/
public class nineteen {
public static void main(String[] args) {
int result = Solution.countTexts("222222222222222222222222222222222222");
System.out.println(result);
}

static class Solution {
public static int countTexts(String str) {
int MOD = (int) 1e9 + 7;
int len = str.length();
// 动态规划数组
int[] dp = new int[len + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= len; i++) {
dp[i] = dp[i - 1];
char c = str.charAt(i - 1);
if (c == str.charAt(i - 2)) {
dp[i] = (dp[i] + dp[i - 2]) % MOD;

if (i > 2 && c == str.charAt(i - 3)) {
dp[i] = (dp[i] + dp[i - 3]) % MOD;

if ((c == '7' || c == '9') && i > 3
&& c == str.charAt(i - 4)) {
dp[i] = (dp[i] + dp[i - 4]) % MOD;
}
}
}
}
return dp[len];
}
}
}