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.
思路:此题刚开始有点想当然了,以为是1对1的严格交错,后面才发现并不是,交错事字符串的个数是不确定的。
后面只好参考网上的资料,用动态规划求解。
2-dimension dp:
这是一个二维的动态规划,
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbcbcac"
上面的图十分清楚,我也是在这个图的基础上理解并写出的代码。
代码如下:
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { /** * 动态规划求解 * 参考资料:http://blog.csdn.net/doc_sgl/article/details/11714793 */ int len1 = s1.length(); int len2 = s2.length(); int len3 = s3.length(); if(len1 + len2 != len3){ return false; } boolean[][] f = new boolean[len1+1][len2+1]; f[0][0] = true;//第一个设置为true for(int i = 0; i < len1+1;i++){ for(int j = 0; j < len2+1; j++){ //i>0,j>0的条件是摒除i=0j=0的值 if(j > 0){ f[i][j] = f[i][j-1]&&(s3.charAt(i+j-1) == s2.charAt(j-1)); } if(i > 0){ f[i][j] = f[i][j] || ( f[i-1][j]&&(s3.charAt(i+j-1) == s1.charAt(i-1))); } } } return f[len1][len2]; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-15 16:07:40