1.题目
给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。
比如 s1 = "aabcc" s2 = "dbbca"
- 当 s3 = "aadbbcbcac",返回 true.
- 当 s3 = "aadbbbaccc", 返回 false.
2.算法
这是动态规划的题目,递推关系式为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 boolean isInterleave(String s1, String s2, String s3)
{
// write your code here
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()];
}
原帖连接http://blog.youkuaiyun.com/linhuanmars/article/details/24683159