题目
判断两个字符串 s1 和 s2 是否可以拼接出 s3
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.
思路
用类似于 Distinct Subsequences 的递归思想
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s1.size()+s2.size()!=s3.size())
return false;
if(s1.size()==0 && s2==s3)
return true;
if(s2.size()==0 && s1==s3)
return true;
return match(s1,s2,s3,0,0);
}
bool match(string &s1, string &s2, string &s3, int indS1, int indS3)
{
bool flag = false;
if(indS1>=s1.size() || indS3>=s3.size())
return false;
if(s3[indS3]==s1[indS1])
{
s3.erase(s3.begin()+indS3);
if(indS1==s1.size()-1)
{
if(s2==s3)
return true;
}
else {
flag = flag|| match(s1,s2,s3,indS1+1,indS3);
}
s3.insert(s3.begin()+indS3,1,s1[indS1]);
}
flag = flag|| match(s1,s2,s3,indS1,indS3+1);
return flag;
}
};
结果:对大数据 Run Status: Time Limit Exceeded