# #29 Interleaving String

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()];
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：#29 Interleaving String 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)