Leetcode Note: Interlaving String
I. 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.
Ii. Question Analysis
This problem can be solved using two-dimensional dynamic planning. The following table shows the intuitive matching process:
Set the status of a gridk[i][j]
, Indicatess1[i]
Ors2[j]
, Ands3[i+j]
.s3
Ands1
Ands2
Matching can be divided into the following two situations:
Ifs1
The last character of is equals3
The last characterk[i][j]=k[i-1][j]
;
Ifs2
The last character of is equals3
The last characterk[i][j]=k[i][j-1]
.
Therefore, the state transition equation is as follows:
f[i][j] = (s1[i - 1] == s3 [i + j - 1] && f[i - 1][j]) "| (s2[j - 1] == s3 [i + j - 1] && f[i][j - 1]);
Iii. Sample Code
# Include
# Include
# Include
Using namespace std; class Solution {public: bool isInterleave (string s1, string s2, string s3) {if (s3.size ()! = S1.size () + s2.size () return false; if (s3 [0]! = S1 [0] & s3 [0]! = S2 [0]) return false; vector
> K (s1.size () + 1, vector
(S2.size () + 1, false); k [0] [0] = true; // set the boundary for (size_t I = 1; I <= s1.size (); ++ I) k [I] [0] = (s1 [I-1] = s3 [I-1]) & k [I-1] [0]; for (size_t j = 1; j <= s2.size (); ++ j) k [0] [j] = (s2 [j-1] = s3 [j-1]) & k [0] [j-1]; for (size_t I = 1; I <= s1.size (); ++ I) {for (size_t j = 1; j <= s2.size (); ++ j) {k [I] [j] = (s1 [I-1] = s3 [I + j-1]) & k [I-1] [j]) | (s2 [j-1] = s3 [I + j-1]) & k [I] [j-1]);} return k [s1.size ()] [s2.size ()] ;}};
During programming, pay attention to the boundary condition and the array subscript.