标签:
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+1][j+1]表示s1[0...i]和s2[0...j]是否能拼成s3[i+j+1],那么在dp[i][j+1]=true的情况下,只要s1[i+1]=s3[i+j+1]的话,那么dp[i+1][j+1]就满足,同样dp[i+1][j]的情况也是一样的。
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { int m = s1.length(), n = s2.length(); if (m + n != s3.length()) return false; boolean dp[][] = new boolean[m+1][n+1]; dp[0][0] = true; for (int i = 0; i < n; i++) dp[0][i+1] = dp[0][i] && (s2.charAt(i) == s3.charAt(i)); for (int i = 0; i < m; i++) dp[i+1][0] = dp[i][0] && (s1.charAt(i) == s3.charAt(i)); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) dp[i+1][j+1] = (dp[i][j+1] && (s1.charAt(i) == s3.charAt(i+j+1)) || (dp[i+1][j] && (s2.charAt(j) == s3.charAt(i+j+1)))); return dp[m][n]; } }
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45252915