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.
动态规划
思路
state: dp[i][j] s1取前i个字符 s2取前j个字符 s3取前i+1字符 是否能匹配
function: 如果最后一位(i+j位)与s1的最后一位(i位)相等 dp[i][j] = dp[i-1][j]
与s2最后一位相等则dp[i][j] = dp[i][j-1]
initial: dp[0][0] = true dp[i][0] dp[0][j]看s1 s2 s3比较
返回: dp[s1.length][s2.length]
复杂度
时间O(mn) 空间O(mn)
代码
public boolean isInterleave(String s1, String s2, String s3) {
if (s1.length() + s2.length() != s3.length()) {
return false;
}
boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];
dp[0][0] = true;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s3.charAt(i) && dp[i][0] == true) {
dp[i + 1][0] = true;
}
}
for (int j = 0; j < s2.length(); j++) {
if (s2.charAt(j) == s3.charAt(j) && dp[0][j] == true) {
dp[0][j + 1] = true;
}
}
for (int i = 1; i <= s1.length(); i++) {
for (int j = 1; j <= s2.length(); j++) {
if (s3.charAt(i + j - 1) == s1.charAt(i - 1) && dp[i - 1][j] == true) {
dp[i][j] = true;
}
if (s3.charAt(i + j - 1) == s2.charAt(j - 1) && dp[i][j - 1] == true) {
dp[i][j] = true;
}
}
}
return dp[s1.length()][s2.length()];
}
一维动态规划
复杂度
时间O(m*n) 空间O(min(m,n))
代码
public boolean isInterleave(String s1, String s2, String s3) {
if (s1.length() + s2.length() != s3.length()) {
return false;
}
String maxWord = s1.length() > s2.length() ? s1 : s2;
String minWord = s1.length() > s2.length() ? s2 : s1;
boolean[]dp = new boolean[minWord.length() + 1];
dp[0] = true;
for (int i = 0; i < minWord.length(); i++) {
if (minWord.charAt(i) == s3.charAt(i) && dp[i] == true) {
dp[i + 1] = true;
}
}
for (int i = 1; i <= maxWord.length(); i++) {
dp[0] = dp[0] && maxWord.charAt(i - 1) == s3.charAt(i - 1);
for (int j = 1; j <= minWord.length(); j++) {
dp[j] = s3.charAt(i + j - 1) == maxWord.charAt(i - 1) && dp[j] == true || s3.charAt(i + j - 1) == minWord.charAt(j - 1) && dp[j - 1] == true;
//此处不能再用if判断, 因为dp[j]已经有值 必须要赋值true/false
}
}
return dp[minWord.length()];
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。