Description
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example:
|
|
Explanation: aadbbcbcac, aadbbcbcac are all valid interpretations for the interleaving.
Notice:
- The order of the strings cannot be changed, which indicates that we can construct
s3
usings1
ands2
from their substrings. - Different ways of interleaving can led to same results.
Example of constructing a string
We define $dp[i][j]$ as: If $a3[0, i+j]$ can be constructed by $a1[0, i]$ and $a2[0, j]$ We have 2 choices to construct $a3[0, i+j+1]$: using $a1[i+1]$ or $a2[j+1]$
|
|
So we have 2 ways to get the needed dp[i][j]
|
|
i.e.
|
|
Corner Cases
If $i=0, j=5$, it represents that if $a3[0, 5]$ can be constructed by $s1=\varnothing$ and $s2[0,5]$, we only need to check that if $s2[0,5] = s3[0,5]$
If we use 0-based index, this situation corresponding to dp[-1][4]
, which is not quite convenience. Using 1-based indexing we could initialize the first row and col and then calculating the dp table from dp[1][1]
0 | d | b | b | c | a | |
---|---|---|---|---|---|---|
0 | T | F | F | F | F | F |
a | T | F | F | F | F | F |
a | T | T | T | T | F | F |
b | F | T | T | F | F | F |
c | F | F | T | T | T | T |
c | F | F | F | T | F | T |
|
|
Note:
- Under 1-based indexing, take care of the indexing on
s1
,s2
ands3
.