题目为 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
思路为深度递归,代码复杂度 2^n n为s3的长度 代码如下 未通过 超时
public bool IsInterleave(string s1, string s2, string s3) {
if (s3.Length!=(s1.Length+s2.Length))
{
return false;
}
GetInterDetail(s1, s2, s3);
return resInter;
}
bool resInter = false;
public void GetInterDetail(string s1, string s2, string s3)
{
if (s1.Length==0&&s2.Length==0&&s3.Length==0)
{
resInter = true;
return;
}
if (s1.Length>0&&s1.Substring(0,1)== s3.Substring(0, 1))
{
GetInterDetail(s1.Substring(1), s2, s3.Substring(1));
}
if (s2.Length > 0 && s2.Substring(0, 1) == s3.Substring(0, 1))
{
GetInterDetail(s1, s2.Substring(1), s3.Substring(1));
}
return;
}
看了题解对代码进行了优化,加入一个二维布尔数组,存储是否已经做过判断,代码如下
public bool IsInterleave(string s1, string s2, string s3)
{
bool[,] boolRes=new bool[s1.Length+1,s2.Length+1];
if (s3.Length!=(s1.Length+s2.Length))
{
return false;
}
return GetInterDetail(s1, s2, s3, boolRes);
}
public bool GetInterDetail(string s1, string s2, string s3, bool[,] boolRes)
{
if (s1.Length==0&&s2.Length==0&&s3.Length==0)
{
return true;
}
if (boolRes[s1.Length,s2.Length])
{
return false;
}
if (s1.Length>0&&s1.Substring(0,1)== s3.Substring(0, 1))
{
if (GetInterDetail(s1.Substring(1), s2, s3.Substring(1), boolRes))
{
return true;
}
}
if (s2.Length > 0 && s2.Substring(0, 1) == s3.Substring(0, 1))
{
if (GetInterDetail(s1, s2.Substring(1), s3.Substring(1), boolRes))
{
return true;
}
}
boolRes[s1.Length, s2.Length] = true;
return false;
}