Total Accepted: 48816 Total Submissions: 217231 Difficulty: Hard
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(char* s1, char* s2, char* s3) {
int dp[100][100];
int stack[100][3];
int ss = 0;
int i=0,j=0,index=0;
dp[0][0]=0;
while(s3[index]!='\0')
{
if(s3[index] == s1[i]||s3[index]== s2[j])
{
if (s3[index] == s1[i]&&s3[index]==s2[j]&&(dp[j+1][i]!=1||dp[j][i+1]!=1)) {
stack[ss][0]=index;
stack[ss][1]=i;
stack[ss][2]=j;
ss++;
}
if(s3[index] ==s1[i]&&dp[j][i+1]==0)
{
index++;
i++;
dp[j][i]=1;
continue;
}
else if(s3[index]==s2[j]&&dp[j+1][i]==0)
{
index++;
j++;
dp[j][i]=1;
continue;
}
}
if (ss<1) {
return false;
}
{
index = stack[ss-1][0];
i=stack[ss-1][1];
j=stack[ss-1][2];
ss--;
continue;
}
}
return true;
}