- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 73 lines of C++ from the credited upstream file 1397.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int findGoodStrings(int n, string s1, string s2, string evil) {4 vector<vector<vector<vector<int>>>> mem(5 n, vector<vector<vector<int>>>(6 evil.length(), vector<vector<int>>(2, vector<int>(2, -1))));7 8 9 vector<vector<int>> nextMatchedCount(evil.length(), vector<int>(26, -1));10 return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount,11 mem);12 }13 14 private:15 static constexpr int kMod = 1'000'000'007;16 17 18 19 20 21 int count(const string& s1, const string& s2, const string& evil, int i,22 int matchedEvilCount, bool isS1Prefix, bool isS2Prefix,23 const vector<int>& evilLPS, vector<vector<int>>& nextMatchedCount,24 vector<vector<vector<vector<int>>>>& mem) {25 26 if (matchedEvilCount == evil.length())27 return 0;28 29 if (i == s1.length())30 return 1;31 int& res = mem[i][matchedEvilCount][isS1Prefix][isS2Prefix];32 if (res != -1)33 return res;34 res = 0;35 const char minLetter = isS1Prefix ? s1[i] : 'a';36 const char maxLetter = isS2Prefix ? s2[i] : 'z';37 for (char c = minLetter; c <= maxLetter; ++c) {38 const int nextMatchedEvilCount = getNextMatchedEvilCount(39 nextMatchedCount, evil, matchedEvilCount, c, evilLPS);40 res += count(s1, s2, evil, i + 1, nextMatchedEvilCount,41 isS1Prefix && c == s1[i], isS2Prefix && c == s2[i], evilLPS,42 nextMatchedCount, mem);43 res %= kMod;44 }45 return res;46 }47 48 49 50 vector<int> getLPS(const string& pattern) {51 vector<int> lps(pattern.length());52 for (int i = 1, j = 0; i < pattern.length(); ++i) {53 while (j > 0 && pattern[j] != pattern[i])54 j = lps[j - 1];55 if (pattern[i] == pattern[j])56 lps[i] = ++j;57 }58 return lps;59 }60 61 62 int getNextMatchedEvilCount(vector<vector<int>>& nextMatchedCount,63 const string& evil, int j, char currLetter,64 const vector<int>& evilLPS) {65 int& res = nextMatchedCount[j][currLetter - 'a'];66 if (res != -1)67 return res;68 while (j > 0 && evil[j] != currLetter)69 j = evilLPS[j - 1];70 return res = (evil[j] == currLetter ? j + 1 : j);71 }72};73