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
遇到字符串问题一定要优先考虑dp,我们可以用一个二维数组dp[I][j],代表取s1的前I位和s2的前j位,与s3的前I+j位进行比较,那么递推关系是什么呢?
如果第s3[i+j]=s1[I],那么我们需要判断s3[I-1][j]是否为true,即前I+j-1位与s1取I-1位、s2取j位是否相等,如果相等,则s3[I][j]才能为true,同理j,代码:
public boolean isInterleave(String s1, String s2, String s3) { int m=s1.length(),n=s2.length(); if(m+n!=s3.length())return false; boolean[][] res=new boolean[m+1][n+1]; res[0][0]=true; for(int j=1;j<=n;j++){ if(s2.charAt(j-1)==s3.charAt(j-1)&&res[0][j-1]) res[0][j]=true; } for(int i=1;i<=m;i++){ if(s1.charAt(i-1)==s3.charAt(i-1)&&res[i-1][0]) res[i][0]=true; } for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ int k=i+j-1; if((s3.charAt(k)==s1.charAt(i-1)&&res[i-1][j])||(s3.charAt(k)==s2.charAt(j-1)&&res[i][j-1])) res[i][j]=true; } } return res[m][n]; }