# #29 Interleaving String

41人阅读 评论(0)

Given three strings: s1s2s3, determine whether s3 is formed by the interleaving of s1 and s2.

Example

For s1 = "aabcc", s2 = "dbbca"

• When s3 = "aadbbcbcac", return true.
• When s3 = "aadbbbaccc", return false.
Challenge

O(n2) time or better

Mycode（AC ＝ 23ms):

class Solution {
public:
/**
* Determine whether s3 is formed by interleaving of s1 and s2.
* @param s1, s2, s3: As description.
* @return: true of false.
*/
bool isInterleave(string s1, string s2, string s3) {
if (s1.size() + s2.size() != s3.size()) return false;

vector<vector<bool>> dp(s1.size() + 1, vector<bool>(s2.size() + 1, false));

dp[0][0] = true;
// initialize dp[i][0] and dp[0][i]
for (int i = 1; i <= s1.size(); i++) {
dp[i][0] = dp[i - 1][0] && s3[i - 1] == s1[i - 1];
}
for (int i = 1; i <= s2.size(); i++) {
dp[0][i] = dp[0][i - 1] && s3[i - 1] == s2[i - 1];
}

// do dp
for (int i = 1; i <= s1.size(); i++) {
for (int j = 1; j <= s2.size(); j++) {
dp[i][j] = (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]) ||
(dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
}
}

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：11918次
• 积分：2240
• 等级：
• 排名：第16771名
• 原创：221篇
• 转载：1篇
• 译文：0篇
• 评论：10条
文章分类
文章存档
阅读排行
评论排行