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.
bool isInterleave(string s1, string s2, string s3) {
// if length does not match
if((s1.length()+s2.length())!=s3.length())
return false;
if(s1.length()==0)
if(s2.compare(s3)==0)
return true;
else
return false;
if(s2.length()==0)
if(s1.compare(s3)==0)
return true;
else
return false;
// if the first char does not match
if(s1.at(0)!=s3.at(0) && s2.at(0)!=s3.at(0))
return false;
// if the first char of s1 matches with the first char of s3
if(s1.at(0)==s3.at(0) && s2.at(0)!=s3.at(0) )
return isInterleave(s1.substr(1,s1.length()-1), s2, s3.substr(1, s3.length()-1) );
// if the first char of s2 matches with the first char of s3
if( s1.at(0)!=s3.at(0) && s2.at(0)==s3.at(0) )
return isInterleave(s1, s2.substr(1,s2.length()-1), s3.substr(1, s3.length()-1) );
// if the first char of s1 and s2 matches with the first char of s3
if(s1.at(0)==s3.at(0) && s2.at(0)==s3.at(0))
return (isInterleave(s1.substr(1,s1.length()-1), s2, s3.substr(1, s3.length()-1) ) ) ||( isInterleave(s1, s2.substr(1,s2.length()-1), s3.substr(1, s3.length()-1) ) );
}
在Leetcode的服务器上,在测试非常长的字符串时,上面的代码给出了超时的错误。
可以考虑用动态规划的思想,把上面递归的中间结果存在一个表中。代码如下:
bool isInterleave(string s1, string s2, string s3) {
if((s1.length()+s2.length())!=s3.length())
return false;
vector<bool> table_row (s2.length()+1, false);
vector<vector<bool>> table(s1.length()+1, table_row ); // this table stores the intermediate results
for(int i=0; i<=s1.length(); i++)
if(s1.substr(0,i).compare(s3.substr(0,i)) ==0)
table[i][0] = true; // initialize the table
for(int j=0; j<=s2.length(); j++)
if(s2.substr(0,j).compare(s3.substr(0,j)) ==0)
table[0][j] = true; // initialize the table
for(int i=1; i<=s1.length(); i++)
for(int j=1; j<=s2.length(); j++)
{
if( s1.at(i-1)==s3.at(i+j-1) && s2.at(j-1)!=s3.at(i+j-1) )
table[i][j] = table[i-1][j];
if( s1.at(i-1)!=s3.at(i+j-1) && s2.at(j-1)==s3.at(i+j-1) )
table[i][j] = table[i][j-1];
if( s1.at(i-1)==s3.at(i+j-1) && s2.at(j-1)==s3.at(i+j-1) )
table[i][j] = table[i-1][j] || table[i][j-1];
}
return table[s1.length()][s2.length()];
}