题目:Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
题目分析:给定两个字符串s1,s2,判断字符串s3是否能由s1,s2的交叉链接组成。
很显然,这种字符串匹配的题容易想到递归,但一定会超时……所以考虑用动态规划的方法。
思路:动态规划要利用数组。使用一个二维数组judge[][],其中judge[i][j]表示字符串 s1 前 i 项, s2 前 j 项已与 s3 前i+j 项匹配。
每计算一项judge[i][j],要看其左边一项,即judge[i][j-1]是否为true及s2的第j项是否与s3匹配;或者其上边一项,即judge[i-1][j-1]是否为true及s1的第i项是否与s3匹配;
举例:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
s1\s2 | d | b | b | c | a | |
---|---|---|---|---|---|---|
true | ||||||
a | true | |||||
a | true | true | true | true | true | |
b | true | true | true | |||
c | true | true | true | true | ||
c | true | true |
代码:
bool isInterleave(string s1, string s2, string s3) {
int len1=s1.length();
int len2=s2.length();
int len3=s3.length();
if(len1+len2!=len3) return false;
bool **judge;
judge=new bool*[len1+1];
for(int i=0;i<len1+1;i++){
judge[i]=(bool *)calloc(sizeof(bool),(len2+1));
}
for(int i=0;i<=len1;i++){
for(int j=0;j<=len2;j++){
if(i==0&&j==0)
judge[i][j]= true;
else if(i==0)
judge[i][j]= s2[j-1]==s3[j-1] && judge[i][j-1];
else if(j==0)
judge[i][j]= s1[i-1]==s3[i-1] && judge[i-1][j];
else
judge[i][j]= (s1[i-1]==s3[i+j-1] && judge[i-1][j])||( s2[j-1]==s3[i+j-1] && judge[i][j-1]);
}
}
return judge[len1][len2];
}