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.
Hide TagsDynamic Programming StringIdea one: DFS, recursion, timeout time Limit exceeded
classSolution { Public: BOOLDfsintIDX1,intIDX2,intIDX3,stringS1,stringS2,stringS3) { //cout << "idx1\t" << idx1 << Endl; //cout << "idx2\t" << idx2 << Endl; //cout << "idx3\t" << idx3 << Endl; if(Idx3 = =s3.size ()) { if(idx2 = = S2.size () && idx1 = =s1.size ())return true; Else return false; } if(s1[idx1] = = s3[idx3] && dfs (idx1+1, idx2,idx3+1, S1,S2,S3)) return true; if(S2[IDX2] = = s3[idx3] && dfs (idx1,idx2+1, idx3+1, S1,S2,S3)) return true; return false; } BOOLIsinterleave (stringS1,stringS2,stringS3) { if((S1.size () + s2.size ())! =s3.size ())return false; returnDfs0,0,0, S1,S2,S3); } };
IDEA two: DP
State F[i][j], representing S1[0,i-1] and s2[0,j-1], matching s3[0, i+j-1]. If the last character of S1, etc.
The last character of S3, then f[i][j]=f[i-1][j]; If the last character of S2 equals the last character of S3,
Then F[i][j]=f[i][j-1]. So the state transfer 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]);
classSolution { Public: BOOLIsinterleave (stringS1,stringS2,stringS3) { if((S1.size () + s2.size ())! =s3.size ())return false; //F[i][j] indicates s1[0 ~ i-1] and s2[0 ~ j-1] can consititue s3[0 ~ i+j-1]vector<BOOL> tmp (s2.size () +1,false);//Colum Sizevector<vector<BOOL> > F (s1.size () +1, TMP);//Row Sizef[0][0] =true;//indicate null str + NULL STR can constitue null str for(inti =1; I <=s2.size (); i++ ) { if(f[0][i-1] && s2[i-1] = = s3[i-1]) f[0][i] =true; } for(inti =1; I <=s1.size (); i++ ) { if(f[i-1][0] && s1[i-1] = = s3[i-1]) f[i][0] =true; } for(inti =1; I <= s1.size (); i++) { for(intj =1; J <= S2.size (); J + +) { if((f[i-1][J] && s1[i-1] = = s3[i+j-1]) ||(F[i][j-1] && s2[j-1] = = s3[i+j-1])) F[i][j]=true; } } returnf[s1.size ()][s2.size ()]; }};
[Leetcode] Interleaving String