- 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
- 66 lines of Java from the credited upstream file 1397.java.
- 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 int findGoodStrings(int n, String s1, String s2, String evil) {3 Integer[][][][] mem = new Integer[n][evil.length()][2][2];4 5 6 Integer[][] nextMatchedCount = new Integer[evil.length()][26];7 return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount, mem);8 }9 10 private static final int MOD = 1_000_000_007;11 12 13 14 15 16 private int count(final String s1, final String s2, final String evil, int i,17 int matchedEvilCount, boolean isS1Prefix, boolean isS2Prefix, int[] evilLPS,18 Integer[][] nextMatchedCount, Integer[][][][] mem) {19 20 if (matchedEvilCount == evil.length())21 return 0;22 23 if (i == s1.length())24 return 1;25 final int k1 = isS1Prefix ? 1 : 0;26 final int k2 = isS2Prefix ? 1 : 0;27 if (mem[i][matchedEvilCount][k1][k2] != null)28 return mem[i][matchedEvilCount][k1][k2];29 mem[i][matchedEvilCount][k1][k2] = 0;30 final char minChar = isS1Prefix ? s1.charAt(i) : 'a';31 final char maxChar = isS2Prefix ? s2.charAt(i) : 'z';32 for (char c = minChar; c <= maxChar; ++c) {33 final int nextMatchedEvilCount =34 getNextMatchedEvilCount(nextMatchedCount, evil, matchedEvilCount, c, evilLPS);35 mem[i][matchedEvilCount][k1][k2] +=36 count(s1, s2, evil, i + 1, nextMatchedEvilCount, isS1Prefix && c == s1.charAt(i),37 isS2Prefix && c == s2.charAt(i), evilLPS, nextMatchedCount, mem);38 mem[i][matchedEvilCount][k1][k2] %= MOD;39 }40 return mem[i][matchedEvilCount][k1][k2];41 }42 43 44 45 private int[] getLPS(final String pattern) {46 int[] lps = new int[pattern.length()];47 for (int i = 1, j = 0; i < pattern.length(); ++i) {48 while (j > 0 && pattern.charAt(j) != pattern.charAt(i))49 j = lps[j - 1];50 if (pattern.charAt(i) == pattern.charAt(j))51 lps[i] = ++j;52 }53 return lps;54 }55 56 57 private int getNextMatchedEvilCount(Integer[][] nextMatchedCount, final String evil, int j,58 char currChar, int[] lps) {59 if (nextMatchedCount[j][currChar - 'a'] != null)60 return nextMatchedCount[j][currChar - 'a'];61 while (j > 0 && evil.charAt(j) != currChar)62 j = lps[j - 1];63 return nextMatchedCount[j][currChar - 'a'] = (evil.charAt(j) == currChar ? j + 1 : j);64 }65}66