1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { public boolean isInterleave(String s1, String s2, String s3) { return isInterleave(s1, s2, s3, new HashMap<>()); }
private boolean isInterleave(String s1, String s2, String s3, Map<String, Boolean> calcMap) { String temp = s1 + "#" + s2; if (calcMap.containsKey(temp)) { return calcMap.get(temp); }
boolean result = false; if (s1.length() == 0) { result = s2.equals(s3); } else if (s2.length() == 0) { result = s1.equals(s3); } else if (s1.charAt(0) == s2.charAt(0) && s1.charAt(0) == s3.charAt(0)) { result = isInterleave(s1.substring(1), s2, s3.substring(1), calcMap) || isInterleave(s1, s2.substring(1), s3.substring(1), calcMap); } else if (s1.charAt(0) == s3.charAt(0)) { result = isInterleave(s1.substring(1), s2, s3.substring(1), calcMap); } else if (s2.charAt(0) == s3.charAt(0)) { result = isInterleave(s1, s2.substring(1), s3.substring(1), calcMap); }
calcMap.put(temp, result); return result; } }
|