|
| 1 | +# https://leetcode.com/problems/interleaving-string/description/ |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + |
| 6 | + def isInterleaveUtil(self, s1, s2, s3, interleave_str, s1_pos, s2_pos, memo): |
| 7 | + if s1_pos < len(s1) and s2_pos < len(s2): |
| 8 | + if memo[s1_pos][s2_pos]: |
| 9 | + return False |
| 10 | + memo[s1_pos][s2_pos] = True |
| 11 | + |
| 12 | + if s1_pos == len(s1) and s2_pos == len(s2) and interleave_str == s3: |
| 13 | + return True |
| 14 | + |
| 15 | + ans = False |
| 16 | + if s1_pos < len(s1) and s3[s1_pos + s2_pos] == s1[s1_pos]: |
| 17 | + ans |= self.isInterleaveUtil( |
| 18 | + s1, s2, s3, interleave_str + s1[s1_pos], s1_pos + 1, s2_pos, memo) |
| 19 | + |
| 20 | + if not ans and s2_pos < len(s2) and s3[s1_pos + s2_pos] == s2[s2_pos]: |
| 21 | + ans |= self.isInterleaveUtil( |
| 22 | + s1, s2, s3, interleave_str + s2[s2_pos], s1_pos, s2_pos + 1, memo) |
| 23 | + |
| 24 | + return ans |
| 25 | + |
| 26 | + def isInterleave(self, s1, s2, s3): |
| 27 | + """ |
| 28 | + :type s1: str |
| 29 | + :type s2: str |
| 30 | + :type s3: str |
| 31 | + :rtype: bool |
| 32 | + """ |
| 33 | + memo = [[False] * (len(s2)) for i in range(0, len(s1))] |
| 34 | + if len(s1) + len(s2) != len(s3): |
| 35 | + return False |
| 36 | + return self.isInterleaveUtil(s1, s2, s3, "", 0, 0, memo) |
| 37 | + |
| 38 | + |
| 39 | +s1 = "aabcc" |
| 40 | +s2 = "dbbca" |
| 41 | +s3 = "aadbbbaccc" |
| 42 | +assert not Solution().isInterleave(s1, s2, s3) |
0 commit comments