Description:
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.
The most intuitive way is to define a three-dimensional state array f [k] [I] [J] to indicate S3 [0... k-1] Is S1 [0... i] and S2 [0... j.
The status is defined:
F [k] [I] [J] = (F [k-1] [I] [J-1] & S2 [J-1] = S3 [k-1] // the second J-1 character of S2 matches the second K-1 character of S3.
OR = (F [k-1] [I-1] [J] & S1 [I-1] = S3 [k-1] // S1 the second I-1 character with S3's second K-1 characters.
Either of them must meet the conditions.
The Code is as follows:
Version 1: time complexity O (N ^ 3), space complexity O (N ^ 3). Time :~ 200 ms
Version 2: time complexity O (N ^ 2), space complexity O (N ^ 2). Time :~ 4 ms
Version 3: time complexity O (N ^ 2), space complexity O (N). Time :~ 4 ms
Use a rolling array to solve the problem: