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.
解题思路
典型序列型动态规划,Two Sequence DP,Time Complexity - O(m * n), Space Complexity - O(m * n)。
方式一:dfs。boolean[][] f 代表f[i][j],是否被遍历过。如果被遍历过,就不遍历了,直接回退,继续别的搜索。
Runtime: 1 ms runtime beats 93.42% of java submission.
public boolean isInterleave(String a, String b, String c) {
if (a.length() + b.length() != c.length()) return false;
return isInterleave(0, 0, new boolean[a.length() + 1][b.length() + 1], a, b, c);
}
public boolean isInterleave(int i, int j, boolean[][] f, String a, String b, String c) {
if (f[i][j]) return false;
else f[i][j] = true;
if (i == a.length() && j == b.length())
return true;
if (i < a.length() && a.charAt(i) == c.charAt(i + j) && isInterleave(i + 1, j, f, a, b, c))
return true;
if (j < b.length() && b.charAt(j) == c.charAt(i + j) && isInterleave(i, j + 1, f, a, b, c))
return true;
return false;
}
方式二:
和Edit Distance很像。假设我们构建一个棋盘,s1代表行,s2代表列,每次只能向右或者向下走,最后看s3这条路径能不能够从左上到达右下。
Runtime: 6 ms runtime beats 48.44% of java submissions.
public boolean isInterleave2(String s1, String s2, String s3) {
if (s1 == null || s2 == null || s3 == null) return true;
int m = s1.length(), n = s2.length(), s = s3.length();
if (m + n != s) return false;
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int i = 0; i < m + 1; i++) {
for (int j = 0; j < n + 1; j++) {
if (dp[i][j] == true
|| (j - 1 >= 0 && dp[i][j - 1] == true && s2.charAt(j - 1) == s3.charAt(i + j - 1))
|| (i - 1 >= 0 && dp[i - 1][j] == true && s1.charAt(i - 1) == s3.charAt(i + j - 1))) {
dp[i][j] = true;
} else {
dp[i][j] = false;
}
}
}
return dp[m][n];
}