[LeetCode]97. Interleaving String
2017-01-26 18:50
337 查看
https://leetcode.com/problems/interleaving-string/
判断s3是否是s1 & s2交互形成的
首先判断长度不合适直接返回。多开一位数组,初始化数组左侧和上侧。然后dp[i][j]为true仅有两种情况:dp[i - 1][j] 同时s1[i] == s3[i + j - 1];或者,dp[i][j - 1] 同时s2[j] == s3[i + j - 1]
public class Solution {
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 = 1; i < dp.length; i++) {
dp[i][0] = (dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1));
}
for (int i = 1; i < dp[0].length; i++) {
dp[0][i] = (dp[0][i - 1] && s2.charAt(i - 1) == s3.charAt(i - 1));
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
dp[i][j] = ((dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1)));
}
}
return dp[s1.length()][s2.length()];
}
}
判断s3是否是s1 & s2交互形成的
首先判断长度不合适直接返回。多开一位数组,初始化数组左侧和上侧。然后dp[i][j]为true仅有两种情况:dp[i - 1][j] 同时s1[i] == s3[i + j - 1];或者,dp[i][j - 1] 同时s2[j] == s3[i + j - 1]
public class Solution {
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 = 1; i < dp.length; i++) {
dp[i][0] = (dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1));
}
for (int i = 1; i < dp[0].length; i++) {
dp[0][i] = (dp[0][i - 1] && s2.charAt(i - 1) == s3.charAt(i - 1));
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
dp[i][j] = ((dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1)));
}
}
return dp[s1.length()][s2.length()];
}
}
相关文章推荐
- LeetCode 97. Interleaving String
- [Leetcode]@python 97. Interleaving String
- LeetCode 97. Interleaving String
- Leetcode 97. Interleaving String
- [LeetCode]97. Interleaving String
- Leetcode:97. Interleaving String
- [leetcode] 97.Interleaving String
- LeetCode 97. Interleaving String
- leetcode 97.Interleaving String
- [算法作业-动态规划][LeetCode] 97. Interleaving String
- Leetcode 97. Interleaving String
- 个人记录-LeetCode 97. Interleaving String
- [LeetCode] 97. Interleaving String
- 【LeetCode】97. Interleaving String
- [Leetcode] 97. Interleaving String 解题报告
- leetcode 97. Interleaving String
- Leetcode - 97.Interleaving String
- Leetcode 97. Interleaving String
- Leetcode——97. Interleaving String
- Leetcode 97. Interleaving String