Problem solution · Java

Find All Good Strings

Find All Good Strings: a Java solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
66 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Find All Good Strings, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind All Good Strings · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int findGoodStrings(int n, String s1, String s2, String evil) {    Integer[][][][] mem = new Integer[n][evil.length()][2][2];    // nextMatchedCount[i][j] := the number of next matched evil count, where    // there're j matches with `evil` and the current letter is ('a' + j)    Integer[][] nextMatchedCount = new Integer[evil.length()][26];    return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount, mem);  }   private static final int MOD = 1_000_000_007;   // Returns the number of good strings for s[i..n), where there're j matches  // with `evil`, `isS1Prefix` indicates if the current letter is tightly bound  // for `s1` and `isS2Prefix` indicates if the current letter is tightly bound  // for `s2`.  private int count(final String s1, final String s2, final String evil, int i,                    int matchedEvilCount, boolean isS1Prefix, boolean isS2Prefix, int[] evilLPS,                    Integer[][] nextMatchedCount, Integer[][][][] mem) {    // s[0..i) contains `evil`, so don't consider any ongoing strings.    if (matchedEvilCount == evil.length())      return 0;    // Run out of strings, so contribute one.    if (i == s1.length())      return 1;    final int k1 = isS1Prefix ? 1 : 0;    final int k2 = isS2Prefix ? 1 : 0;    if (mem[i][matchedEvilCount][k1][k2] != null)      return mem[i][matchedEvilCount][k1][k2];    mem[i][matchedEvilCount][k1][k2] = 0;    final char minChar = isS1Prefix ? s1.charAt(i) : 'a';    final char maxChar = isS2Prefix ? s2.charAt(i) : 'z';    for (char c = minChar; c <= maxChar; ++c) {      final int nextMatchedEvilCount =          getNextMatchedEvilCount(nextMatchedCount, evil, matchedEvilCount, c, evilLPS);      mem[i][matchedEvilCount][k1][k2] +=          count(s1, s2, evil, i + 1, nextMatchedEvilCount, isS1Prefix && c == s1.charAt(i),                isS2Prefix && c == s2.charAt(i), evilLPS, nextMatchedCount, mem);      mem[i][matchedEvilCount][k1][k2] %= MOD;    }    return mem[i][matchedEvilCount][k1][k2];  }   // Returns the lps array, where lps[i] is the length of the longest prefix of  // pattern[0..i] which is also a suffix of this substring.  private int[] getLPS(final String pattern) {    int[] lps = new int[pattern.length()];    for (int i = 1, j = 0; i < pattern.length(); ++i) {      while (j > 0 && pattern.charAt(j) != pattern.charAt(i))        j = lps[j - 1];      if (pattern.charAt(i) == pattern.charAt(j))        lps[i] = ++j;    }    return lps;  }   // j := the next index we're trying to match with `currLetter`  private int getNextMatchedEvilCount(Integer[][] nextMatchedCount, final String evil, int j,                                      char currChar, int[] lps) {    if (nextMatchedCount[j][currChar - 'a'] != null)      return nextMatchedCount[j][currChar - 'a'];    while (j > 0 && evil.charAt(j) != currChar)      j = lps[j - 1];    return nextMatchedCount[j][currChar - 'a'] = (evil.charAt(j) == currChar ? j + 1 : j);  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗