-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterleaving_String.py
More file actions
50 lines (32 loc) · 1.02 KB
/
Copy pathInterleaving_String.py
File metadata and controls
50 lines (32 loc) · 1.02 KB
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
42
43
44
45
46
47
48
49
50
"""
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
"""
class Solution:
# @return a boolean
def isInterleave(self, s1, s2, s3):
l1 = len(s1); l2 = len(s2); l3 = len(s3)
if l1+l2 != l3:
return False
# dp[i][j] ==> s1[0:i-1] and s2[0:j-1] interleave at s3[0:i+j-1]
dp = [[False]*(l2+1) for i in range(l1+1)]
# s1 and s2 are empty
dp[0][0] = True
# when s1 is empty ... i = 0
for j in range(1, l2+1):
dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]
# when s2 is empty ... j = 0
for i in range(1, l1+1):
dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]
# the general case s1 and s2 are full
for i in range(1, l1+1):
for j in range(1, l2+1):
dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i+j-1]) or (dp[i][j-1] and s2[j-1] == s3[i+j-1])
return dp[l1][l2]
s = Solution()
print s.isInterleave("aabcc", "dbbca", "aadbbbaccc")