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

Lintcode_29 Interleaving String

2016-06-28 08:03:45

leetcode_question_97 Interleaving String

2013-09-15 22:08:06

Interleaving String -- LeetCode

2014-04-29 04:28:30

【LeetCode】Interleaving String 解题报告

2015-03-21 18:50:13

97 - Interleaving String

2016-03-14 09:39:47

动态规划——字符串的交错组成（interleaving-string）

2016-05-21 21:53:33

leetcode 97 Interleaving String(python)

2016-08-01 22:02:09

97.Interleaving String

2015-05-19 00:10:53

LeetCode 97 — Interleaving String （C++ Python）

2014-07-31 22:44:18

leetCode 97.Interleaving String (交错字符串) 解题思路和方法

2015-07-28 11:02:50

不良信息举报

#29 Interleaving String