LeetCode刷题记92
97. 交错字符串
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if (s3.length() != s1.length() + s2.length()) {
return false;
}
if (s3.length() == 0 && s1.length() == 0 && s2.length() == 0) {
return true;
}
if (s1.length() == 0) {
return s2.compareTo(s3) == 0;
}
if (s2.length() == 0) {
return s1.compareTo(s3) == 0;
}
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 + 1][0] = true;
else break;
}
for (int i = 0; i < s2.length(); i ++) {
if (s2.charAt(i) == s3.charAt(i)) dp[0][i + 1] = true;
else break;
}
for (int i = 1; i <= s1.length(); i ++) {
char a = s1.charAt(i - 1);
for (int j = 1; j <= s2.length(); j ++) {
char b = s2.charAt(j - 1);
char c = s3.charAt(i + j - 1);
if (c == a && c != b) {
dp[i][j] |= dp[i - 1][j];
} else if (c == b && c != a) {
dp[i][j] |= dp[i][j - 1];
} else if (c == a && c == b) {
dp[i][j] |= dp[i - 1][j] || dp[i][j - 1];
}
}
}
return dp[s1.length()][s2.length()];
}
}
一开始一直错,后来有参考题解,我太菜了。
4/5
92/150