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.
Java:
http://blog.csdn.net/linhuanmars/article/details/24683159
动态规划
递归式:
res[i][j] = res[i-1][j]&&s1.charAt(i-1)==s3.charAt(i+j-1) || res[i][j-1]&&s2.charAt(j-1)==s3.charAt(i+j-1)
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (s1 == null || s2 == null || s3 == null) return false;
if (s1.length() + s2.length() != s3.length()) return false;
String minWord=s1.length()>s2.length()?s2:s1;
String maxWord=s1.length()>s2.length()?s1:s2;
boolean[] res=new boolean[minWord.length()+1];
res[0]=true;
for(int i=0;i<minWord.length();i++)
{
res[i+1]=res[i]&&minWord.charAt(i)==s3.charAt(i);
}
for(int i=0;i<maxWord.length();i++)
{
res[0]=res[0]&&maxWord.charAt(i)==s3.charAt(i);
for(int j=0;j<minWord.length();j++)
{
res[j+1]=res[j+1]&&maxWord.charAt(i)==s3.charAt(i+j+1)||res[j]&&minWord.charAt(j)==s3.charAt(i+j+1);
}
}
return res[minWord.length()];
}
}