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 in Java:(Dynamic)
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if(s1=="") return s2.equals(s3);
if(s2=="") return s1.equals(s3);
int len1=s1.length(), len2 = s2.length(), len3 = s3.length();
if(len3!=len1+len2) return false;
boolean[][] opj = new boolean[len1+1][len2+1];
//opj[i][j] denotes if s1[0...i-1] and s2[0...j-1] can form s3[0...i+j-1].
//so opj[len1][len2] denotes if s1[0...len1-1] and s2[0...len2-1] can from s3[0...len1+len2-1],
//which is the answer we need.
opj[0][0]=true;
for(int j=1; j<len2+1; j++) opj[0][j] = s2.charAt(j-1)==s3.charAt(j-1);
for(int i=1; i<len1+1; i++) opj[i][0] = s1.charAt(i-1)==s3.charAt(i-1);
for(int i=1; i<len1+1; i++){
for(int j=1; j<len2+1; j++){
opj[i][j] = opj[i-1][j]&&s1.charAt(i-1)==s3.charAt(i+j-1)|| //add char in s1
opj[i][j-1]&&s2.charAt(j-1)==s3.charAt(i+j-1); //add char in s2
}
}
return opj[len1][len2];
}
}
Note: 只关心s3[0...i+j-1]是否能由s1[0...i-1]和s2[0...j-1]形成,不关心之前怎样形成的具体过程。
而在s3[0...i+j-2]合法的前提下,要s3[0...i+j-1]也合法,需要由s1或s2中添加一个合法字母。