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
|
class Solution {
int mod = 1000000007;
public int findGoodStrings(int n, String s1, String s2, String evil) {
int[] fail = new int[evil.length()];
for (int i = 1, j = 0; i < evil.length(); i++) {
while (j > 0 && evil.charAt(i) != evil.charAt(j)) j = fail[j-1];
if (evil.charAt(i) == evil.charAt(j)) fail[i] = ++j;
}
Integer[][][][] dp = new Integer[n+1][2][2][evil.length()];
return dfs(0, 1, 1, 0, n, s1, s2, evil, fail, dp);
}
int dfs(int pos, int low, int high, int match, int n, String s1, String s2, String evil, int[] fail, Integer[][][][] dp) {
if (match == evil.length()) return 0;
if (pos == n) return 1;
if (dp[pos][low][high][match] != null) return dp[pos][low][high][match];
int ans = 0;
char from = low==1 ? s1.charAt(pos) : 'a';
char to = high==1 ? s2.charAt(pos) : 'z';
for (char c = from; c <= to; c++) {
int nxt = match;
while (nxt > 0 && c != evil.charAt(nxt)) nxt = fail[nxt-1];
if (c == evil.charAt(nxt)) nxt++;
ans = (ans + dfs(pos+1, low==1&&c==from?1:0, high==1&&c==to?1:0, nxt, n, s1, s2, evil, fail, dp)) % mod;
}
return dp[pos][low][high][match] = ans;
}
}
|