Topic Link: interleaving String
Given S1, S2, S3, find whether S3 are 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 requirement of this problem is to detect whether the string S3 is interleaved by S1 and S2.
This is a dynamic programming topic, using Dp[i, j] to indicate whether the S1 first and the first J characters of the S2 can be interleaved to generate S3 's first i+j characters.
As for the initial values of the DP array, when J equals 0, the value of Dp[i, 0] depends on dp[i-1, 0] is true and s1[i-1] is equal to s3[i-1], i.e.
- Dp[i][0] = dp[i-1][0] && s1[i-1] = = S3[i-1]
Similarly, when I equals 0:
- DP[0][J] = dp[0][j-1] && s2[j-1] = = S3[j-1]
As for the recursive formula, it depends on whether the characters read in the current period are equal to the corresponding characters in the S3:
- If S1[I-1] is the same as s3[i+j-1], the current position S1 can be matched, so if Dp[i-1, J] is true, Dp[i, J] is true.
- If S2[J-1] is the same as s3[i+j-1], the current position S2 can be matched, so if dp[i, J-1] is true, Dp[i, J] is true.
In summary, the recursive formula is Dp[i, j] = (s1[i-1] = = S3[i+j-1] && dp[i-1, j]) | | (S2[j-1] = = S3[i+j-1] && dp[i, j-1]).
Note that if the length of the S1 plus the length of the S2 is not equal to the length of the S3, it returns false directly.
Time complexity: O (NM)
Space complexity: O (NM)
1 class Solution2 {3 Public:4 BOOL Isinterleave(string S1, string S2, string S3)5 {6 int L1 = S1.size(), L2 = S2.size(), L3 = S3.size();7 8 if(L3 != L1 + L2)9 return false;Ten One Vector<Vector<BOOL> > DP(L1 + 1, Vector<BOOL>(L2 + 1, false)); A - DP[0][0] = true; - for(int I = 1; I <= L1; ++ I) the DP[I][0] = DP[I - 1][0] && S1[I - 1] == S3[I - 1]; - for(int J = 1; J <= L2; ++ J) - DP[0][J] = DP[0][J - 1] && S2[J - 1] == S3[J - 1]; - + for(int I = 1; I <= L1; ++ I) - for(int J = 1; J <= L2; ++ J) + DP[I][J] = (S1[I - 1] == S3[I + J - 1] && DP[I - 1][J]) A || (S2[J - 1] == S3[I + J - 1] && DP[I][J - 1]); at - return DP[L1][L2]; - } - };
The problem has also been given the method of BFS.
Reprint please indicate source: Leetcode---97. Interleaving String
Leetcode---97. Interleaving String