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.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
动态规划
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if (s1 == null || s2 == null || s3 == null) {
return false;
}
int s1Len = s1.length();
int s2Len = s2.length();
int s3Len = s3.length();
if (s1Len + s2Len != s3Len) {
return false;
}
boolean[] global = new boolean[s1Len + 1];
// initial
global[0] = true;
for (int i = 1; i <= s1Len; i++) {
global[i] = global[i - 1] && (s1.charAt(i - 1) == s3.charAt(i - 1));
}
for (int j = 1; j <= s2Len; j++) {
global[0] = global[0] && s2.charAt(j - 1) == s3.charAt(j - 1);
for (int i = 1; i <= s1Len; i++) {
global[i] = (s3.charAt(i + j - 1) == s2.charAt(j - 1) && global[i]) || (s3.charAt(i + j - 1) == s1.charAt(i - 1) && global[i - 1]);
}
}
return global[s1Len];
}
}