- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 41 lines of Java from the credited upstream file 87.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 boolean isScramble(String s1, String s2) {3 if (s1.equals(s2))4 return true;5 final String hashKey = s1 + "+" + s2;6 if (mem.containsKey(hashKey))7 return mem.get(hashKey);8 9 int[] count = new int[128];10 11 for (int i = 0; i < s1.length(); ++i) {12 ++count[s1.charAt(i)];13 --count[s2.charAt(i)];14 }15 16 for (final int freq : count)17 if (freq != 0) {18 mem.put(hashKey, false);19 return false;20 }21 22 for (int i = 1; i < s1.length(); ++i) {23 if (isScramble(s1.substring(0, i), s2.substring(0, i)) &&24 isScramble(s1.substring(i), s2.substring(i))) {25 mem.put(hashKey, true);26 return true;27 }28 if (isScramble(s1.substring(0, i), s2.substring(s2.length() - i)) &&29 isScramble(s1.substring(i), s2.substring(0, s2.length() - i))) {30 mem.put(hashKey, true);31 return true;32 }33 }34 35 mem.put(hashKey, false);36 return false;37 }38 39 private Map<String, Boolean> mem = new HashMap<>();40}41