1+ """
2+ # INTERLEAVING STRING
3+
4+ Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.
5+
6+ An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that:
7+
8+ s = s1 + s2 + ... + sn
9+ t = t1 + t2 + ... + tm
10+ |n - m| <= 1
11+ The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...
12+ Note: a + b is the concatenation of strings a and b.
13+
14+ Example 1:
15+
16+ Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
17+ Output: true
18+ Example 2:
19+
20+ Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
21+ Output: false
22+ Example 3:
23+
24+ Input: s1 = "", s2 = "", s3 = ""
25+ Output: true
26+
27+ Constraints:
28+
29+ 0 <= s1.length, s2.length <= 100
30+ 0 <= s3.length <= 200
31+ s1, s2, and s3 consist of lowercase English letters.
32+ """
33+ 34+ class Solution :
35+ def isInterleave (self , s1 : str , s2 : str , s3 : str ) -> bool :
36+ if len (s3 ) != len (s1 ) + len (s2 ):
37+ return False
38+ 39+ return self .checkInterleaving (s3 , s1 , s2 , 0 , 0 , 0 , {})
40+ 41+ def checkInterleaving (self , s1 , s2 , s3 , index1 , index2 , index3 , cache ):
42+ #print(index1, index2, index3)
43+ indexStr = self .getString (index1 , index2 , index3 )
44+ if indexStr in cache :
45+ return cache [indexStr ]
46+ 47+ if index1 == len (s1 ):
48+ cache [indexStr ] = True
49+ return True
50+ 51+ if index2 < len (s2 ) and s1 [index1 ] == s2 [index2 ]:
52+ check = self .checkInterleaving (s1 , s2 , s3 , index1 + 1 , index2 + 1 , index3 , cache )
53+ if check :
54+ return True
55+ 56+ if index3 < len (s3 ) and s1 [index1 ] == s3 [index3 ]:
57+ check = self .checkInterleaving (s1 , s2 , s3 , index1 + 1 , index2 , index3 + 1 , cache )
58+ if check :
59+ return True
60+ 61+ cache [indexStr ] = False
62+ return False
63+ 64+ def getString (self , i1 , i2 , i3 ):
65+ return str (i1 ) + "-" + str (i2 ) + "-" + str (i3 )
0 commit comments