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.youkuaiyun.com/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()];
}
}
本文通过Java实现动态规划算法解决字符串交织问题,详细解释了递归式和具体实现步骤,包括初始化、循环和判断条件,展示了如何通过比较三个字符串s1、s2和s3来判断s3是否由s1和s2交织而成。
800

被折叠的 条评论
为什么被折叠?



