您的位置:首页 > 其它

leetcode@ [97] Interleaving Strings

2015-12-01 12:10 309 查看
https://leetcode.com/problems/interleaving-string/

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.

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if(s1.length() + s2.length() != s3.length()) return false;
if(s1.length() == 0 && s2.length() == 0 && s3.length() == 0) return true;

vector<vector<bool> > dp(s1.length()+1, vector<bool>(s2.length()+1, false));
for(int i=1;i<=s1.length();++i) {
dp[i][0] = (s1.substr(0,i) == s3.substr(0,i))? true: false;
}
for(int j=1;j<=s2.length();++j) {
dp[0][j] = (s2.substr(0,j) == s3.substr(0,j))? true: false;
}

for(int i=1;i<=s1.length();++i) {
for(int j=1;j<=s2.length();++j) {
if(dp[i-1][j] && s1[i-1] == s3[i+j-1]) dp[i][j] = true;
else if(dp[i][j-1] && s2[j-1] == s3[i+j-1]) dp[i][j] = true;
else dp[i][j] = false;
}
}

return dp[s1.length()][s2.length()];
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: