Problem:
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.
Solution: DP
Just note that at the second time to assign value to result[i][j], should "||" the first result[i][j].
Code:
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if (s1.length() + s2.length() != s3.length()) return false;
boolean[][] result = new boolean[s1.length() + 1][s2.length() + 1];
int count = 1;
result[0][0] = true;
while(count <= s1.length() && s1.charAt(count - 1) == s3.charAt(count - 1)) {
result[count][0] = true;
count++;
}
count = 1;
while (count <= s2.length() && s2.charAt(count - 1) == s3.charAt(count - 1)) {
result[0][count] = true;
count++;
}
for (int i = 1; i <= s1.length(); i++) {
for (int j = 1; j <= s2.length(); j++) {
if (s1.charAt(i - 1) == s3.charAt(i + j - 1)) {
result[i][j] = result[i - 1][j];
}
if (s2.charAt(j - 1) == s3.charAt(i + j - 1)) {
result[i][j] = result[i][j - 1] || result[i][j];
}
}
}
return result[s1.length()][s2.length()];
}
}