您的位置:首页 > 其它

leetcode 97: Interleaving String

2015-08-11 10:10 429 查看
Use DP, the dp[i][j] means if the strings are matched when I take length i of s1 and length j of s2 to compare with length i+j of s3.

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int m=s1.length();
int n=s2.length();
if(m+n!=s3.length())
return 0;
vector<bool> a(n+1,0);
vector<vector<bool> > dp(m+1,a);
dp[0][0]=1;
for(int i=1;i<=m;i++)
dp[i][0]=s1[i-1]==s3[i-1]?dp[i-1][0]:0;
for(int i=1;i<=n;i++)
dp[0][i]=s2[i-1]==s3[i-1]?dp[0][i-1]:0;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
{
if(s1[i-1]==s3[i+j-1])
dp[i][j]=dp[i-1][j];
if(s2[j-1]==s3[i+j-1])
dp[i][j]=dp[i][j-1]|dp[i][j];
}
return dp[m]
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: