- 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
- 58 lines of Java from the credited upstream file 3474.java.
- The implementation visibly relies on sequence storage.
- 6 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 String generateString(String str1, String str2) {3 final int n = str1.length();4 final int m = str2.length();5 final int sz = n + m - 1;6 char[] ans = new char[sz];7 boolean[] modifiable = new boolean[sz];8 Arrays.fill(modifiable, true);9 10 11 for (int i = 0; i < n; ++i)12 if (str1.charAt(i) == 'T')13 for (int j = 0; j < m; ++j) {14 final int pos = i + j;15 if (ans[pos] != 0 && ans[pos] != str2.charAt(j))16 return "";17 ans[pos] = str2.charAt(j);18 modifiable[pos] = false;19 }20 21 22 for (int i = 0; i < sz; ++i)23 if (ans[i] == 0)24 ans[i] = 'a';25 26 27 for (int i = 0; i < n; ++i)28 if (str1.charAt(i) == 'F' && match(ans, i, str2)) {29 final int modifiablePos = lastModifiablePosition(i, m, modifiable);30 if (modifiablePos == -1)31 return "";32 ans[modifiablePos] = 'b';33 modifiable[modifiablePos] = false;34 }35 36 return new String(ans);37 }38 39 40 private boolean match(char[] ans, int i, String s) {41 for (int j = 0; j < s.length(); ++j)42 if (ans[i + j] != s.charAt(j))43 return false;44 return true;45 }46 47 48 private int lastModifiablePosition(int i, int m, boolean[] modifiable) {49 int modifiablePos = -1;50 for (int j = 0; j < m; ++j) {51 final int pos = i + j;52 if (modifiable[pos])53 modifiablePos = pos;54 }55 return modifiablePos;56 }57}58