Leetcode 97: Interleaving String

Given s1s2s3, 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 }

 

转载于:https://www.cnblogs.com/liangmou/p/7837184.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值