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 public class Solution { 2 public bool IsInterleave(string s1, string s2, string s3) { 3 int len1 = s1.Length, len2 = s2.Length, len3 = s3.Length; 4 5 if (len1 == 0 || len2 == 0) 6 { 7 return len1 == 0 ? s2 == s3 : s1 == s3; 8 } 9 10 if (len3 != len1 + len2) return false; 11 12 var dp = new bool[len1 + 1, len2 + 1]; 13 14 for (int i = 0; i <= len1; i++) 15 { 16 for (int j = 0; j <= len2; j++) 17 { 18 if (i == 0 && j == 0) 19 { 20 dp[i, j] = true; 21 } 22 else if (i == 0) 23 { 24 dp[i, j] = s2.Substring(0, j) == s3.Substring(0, j); 25 } 26 else if (j == 0) 27 { 28 dp[i, j] = s1.Substring(0, i) == s3.Substring(0, i); 29 } 30 else 31 { 32 dp[i, j] = (s1[i - 1] == s3[i + j -1] && dp[i - 1, j]) || (s2[j - 1] == s3[i + j -1] && dp[i, j - 1]); 33 } 34 } 35 } 36 37 return dp[len1, len2]; 38 } 39 }