Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
用res[i:j]表示 s1的前i位 和s2的前j位是否为 s3的前i+j位的结合体
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if(s1.length() + s2.length() != s3.length()) {
return false;
}
boolean res[][] = new boolean[s1.length()+1][s2.length()+1];
res[0][0] = true;
for(int i=1;i<=s1.length();i++) {
if(s1.charAt(i-1) == s3.charAt(i-1) && res[i-1][0]) {
res[i][0] = true;
}
}
for(int i=1;i<=s2.length();i++) {
if(s2.charAt(i-1) == s3.charAt(i-1) && res[0][i-1]) {
res[0][i] = true;
}
}
for(int i=1;i<=s1.length();i++) {
for(int j=1;j<=s2.length();j++) {
res[i][j] = (s3.charAt(i+j-1) ==s1.charAt(i-1) && res[i-1][j])
|| (s3.charAt(i+j-1) ==s2.charAt(j-1) && res[i][j-1]) ;
}
}
return res[s1.length()][s2.length()];
}
}