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.
classSolution { Public: BOOLIsinterleave (stringS1,stringS2,stringS3) { intL1 = S1.size (), L2 =s2.size (), I, J; if(L1 + L2! =s3.size ())return false; Vector<vector<BOOL>> IsMatch (l1+1, vector<BOOL> (l2+1,false)); ismatch[0][0] =true; for(i =1; I <= L1; i++) { if(s1[i-1] = = s3[i-1]) ismatch[i][0] =true; Else Break; } for(i =1; I <= L2; i++) { if(s2[i-1] = = s3[i-1]) ismatch[0][i] =true; Else Break; } for(i =1; I <= L1; i++) { for(j =1; J <= L2; J + +) {Ismatch[i][j]= ((s1[i-1] = = s3[i+j-1]) && ismatch[i-1][J]) | | ((s2[j-1] = = s3[i+j-1]) && ismatch[i][j-1]); } } returnISMATCH[L1][L2]; }};
Considering:
S1 = A1, A2 ... a (i-1), AI
S2 = b1, b2, .... b (j-1), BJ
S3 = C1, C3, .... C (i+j-1), C (I+J)
Defined
MATCH[I][J] means s1[0..i] and S2[0..J] is matched s3[0..i+j]
So, if ai = = C (i+j), then match[i][j] = Match[i-1][j], which means
S1 = A1, A2 ... a (i-1)
S2 = b1, b2, .... b (j-1), BJ
S3 = C1, C3, .... C (i+j-1)
Same, if BJ = C (i+j), then match[i][j] = match[i][j-1];
Formula:
MATCH[I][J] =
(S3[i+j-1] = = S1[i]) && Match[i-1][j] | |
(S3[i+j-1] = = S2[j]) && Match[i][j-1]
Initialization:
I=0 && j=0, match[0][0] = true;
I=0, s3[j] = = S2[j], match[0][j] |= match[0][j-1]
S3[J]! = S2[j], match[0][j] = false;
J=0, s3[i] = = S1[i], match[i][0] |= match[i-1][0]
S3[i]! = S1[i], match[i][0] = false;
Interleaving string *hard*--determine if S3 is a string that is crossed by S1 and S2