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.思路:用递归超时了,只好用DP,整了个矩阵存结果。
bool isInterleave(string s1, string s2, string s3) {
if(s1.length() + s2.length() != s3.length()) return false;
int i, j;
vector<vector<int> > A(s1.length()+1,vector<int>(s2.length()+1));
A[0][0] = 1;
for(i = 1; i < s1.length() + 1; i++){
if(s1[i-1] == s3[i-1]) A[i][0] = A[i-1][0];
}
for(j = 1; j < s2.length() + 1; j++){
if(s2[j-1] == s3[j-1]) A[0][j] = A[0][j-1];
}
for(i =1; i < s1.length() + 1; i++ ){
for(j =1; j < s2.length() + 1; j++){
if((s1[i-1] == s3[i+j-1] && A[i-1][j] == 1) || (s2[j-1] == s3[i+j-1] && A[i][j-1] == 1) )
A[i][j] = 1;
}
}
if(A[s1.length()][s2.length()] == 1) return true;
else return false;
}
No comments:
Post a Comment