Skip to content

Commit b160862

Browse files
authored
Create find-all-good-strings.cpp
1 parent 711ad1a commit b160862

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

C++/find-all-good-strings.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Time: O(m * n)
2+
// Space: O(m)
3+
4+
class Solution {
5+
public:
6+
int findGoodStrings(int n, string s1, string s2, string evil) {
7+
const auto& prefix = getPrefix(evil);
8+
vector<vector<vector<vector<int>>>> dp(
9+
2, vector<vector<vector<int>>>(
10+
2, vector<vector<int>>(
11+
2, vector<int>(evil.length()))));
12+
dp[0][0][0][0] = 1;
13+
for (int i = 0; i < n; ++i) {
14+
dp[(i + 1) % 2] = vector<vector<vector<int>>>(
15+
2, vector<vector<int>>(
16+
2, vector<int>(evil.length())));
17+
for (int j = 0; j < 2; ++j) {
18+
for (int k = 0; k < 2; ++k) {
19+
const auto min_c = j ? 'a' : s1[i];
20+
const auto max_c = k ? 'z' : s2[i];
21+
for (int l = 0; l < evil.length(); ++l) {
22+
if (!dp[i % 2][j][k][l]) {
23+
continue;
24+
}
25+
for (char c = min_c; c <= max_c; ++c) {
26+
int m = l - 1;
27+
while (m != -1 && evil[m + 1] != c) {
28+
m = prefix[m];
29+
}
30+
if (evil[m + 1] == c) {
31+
++m;
32+
}
33+
if (m + 1 == evil.length()) {
34+
continue;
35+
}
36+
add(&dp[(i + 1) % 2][j || c != s1[i]][k || c != s2[i]][m + 1], dp[i % 2][j][k][l]);
37+
}
38+
}
39+
}
40+
}
41+
}
42+
int result = 0;
43+
for (int j = 0; j < 2; ++j) {
44+
for (int k = 0; k < 2; ++k) {
45+
for (int l = 0; l < evil.length(); ++l) {
46+
add(&result, dp[n % 2][j][k][l]);
47+
}
48+
}
49+
}
50+
return result;
51+
}
52+
53+
private:
54+
vector<int> getPrefix(const string& pattern) {
55+
vector<int> prefix(pattern.length(), -1);
56+
int j = -1;
57+
for (int i = 1; i < pattern.length(); ++i) {
58+
while (j != -1 && pattern[j + 1] != pattern[i]) {
59+
j = prefix[j];
60+
}
61+
if (pattern[j + 1] == pattern[i]) {
62+
++j;
63+
}
64+
prefix[i] = j;
65+
}
66+
return prefix;
67+
}
68+
69+
void add(int *x, int y) {
70+
static const int MOD = 1e9 + 7;
71+
*x = (*x + y) % MOD;
72+
}
73+
};

0 commit comments

Comments
 (0)