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.
It can be done recursively, with each match S1 or S2 in a recursive way. But it will time out.
So consider doing it with dynamic planning.
S1, S2 has only two strings, so it can be flattened into a two-dimensional map to determine if it can go from the upper-left corner to the lower-right corner.
When the S1 arrives at the element I, S2 arrives at the first J element:
On the map, the right step is s2[j-1] match s3[i+j-1].
The next step on the map is s1[i-1] Match s3[i+j-1].
Example: s1= "AA", s2= "AB", s3= "Aaba". The standard 1 is feasible. Finally, return to the lower right corner.
0 A B
0 1 1 0
A 1 1 1
A 1 0 1
classSolution { Public: BOOLIsinterleave (stringS1,stringS2,stringS3) { if(S1.size () +s2.size ()! =s3.size ())return false; //s1.size () +1 by s2.size () +1 matrix representing pathvector<vector<BOOL> > Path (s1.size () +1, vector<BOOL> (s2.size () +1,false)); path[0][0] =true; for(inti =0; I < s1.size () +1; i + +) {//Row for(intj =0; J < S2.size () +1; J + +) {//Col if(i = =0&& J = =0) //Start ; Else if(i = =0) //Go by S2PATH[I][J] = path[i][j-1] && (s2[j-1] = = s3[j-1]); Else if(J = =0) //go by S1PATH[I][J] = path[i-1][J] && (s1[i-1] = = s3[i-1]); ElsePath[i][j]= (path[i][j-1] && (s2[j-1] = = s3[i+j-1])) || (path[i-1][J] && (s1[i-1] = = s3[i+j-1])); } } returnpath[s1.size ()][s2.size ()]; }};
"Leetcode" interleaving String