LeetCode //C - 97. Interleaving String

该篇文章讨论了如何使用动态规划方法判断给定的字符串s3是否可以通过字符串s1和s2的交错方式组成。通过比较长度和构建动态规划表来确定是否存在交错可能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

97. Interleaving String

Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

An interleaving of two strings s and t is a configuration where s and t are divided into n and m
substrings
respectively, such that:

  • s = s 1 + s 2 + . . . + s n s = s_1 + s_2 + ... + s_n s=s1+s2+...+sn
  • t = t 1 + t 2 + . . . + t m t = t_1 + t_2 + ... + t_m t=t1+t2+...+tm
  • ∣ n − m ∣ < = 1 |n - m| <= 1 nm<=1
  • The interleaving is s 1 + t 1 + s 2 + t 2 + s 3 + t 3 + . . .   o r   t 1 + s 1 + t 2 + s 2 + t 3 + s 3 + . . . s_1 + t_1 + s_2 + t_2 + s_3 + t_3 + ...\ or \ t_1 + s_1 + t_2 + s_2 + t_3 + s_3 + ... s1+t1+s2+t2+s3+t3+... or t1+s1+t2+s2+t3+s3+...

Note: a + b is the concatenation of strings a and b.
 

Example 1:

在这里插入图片描述

Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac”
Output: true
Explanation: One way to obtain s3 is:
Split s1 into s1 = “aa” + “bc” + “c”, and s2 into s2 = “dbbc” + “a”.
Interleaving the two splits, we get “aa” + “dbbc” + “bc” + “a” + “c” = “aadbbcbcac”.
Since s3 can be obtained by interleaving s1 and s2, we return true.

Example 2:

Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbbaccc”
Output: false
Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.

Example 3:

Input: s1 = “”, s2 = “”, s3 = “”
Output: true

Constraints:
  • 0 <= s1.length, s2.length <= 100
  • 0 <= s3.length <= 200
  • s1, s2, and s3 consist of lowercase English letters.

From: LeetCode
Link: 97. Interleaving String


Solution:

Ideas:
  • Check if sum of s1 and s2 lengths equals s3 length
  • Use DP to check if s3 can be formed by interleaving s1 and s2
  • DP state is dp[i][j] = true if s3[0…i+j-1] can be formed by interleaving s1[0…i-1] and s2[0…j-1]
Code:
bool isInterleave(char* s1, char* s2, char* s3) {
    int m = strlen(s1);
    int n = strlen(s2);
    int t = strlen(s3);
    
    if (m + n != t) {
        return false;
    }
    
    bool dp[m+1][n+1];
    memset(dp, false, sizeof(dp));
    dp[0][0] = true;
    
    for(int i=0; i<=m; i++) {
        for(int j=0; j<=n; j++) {
            if (i > 0 && s1[i-1] == s3[i+j-1] && dp[i-1][j]) {
                dp[i][j] = true; 
            }
            if (j > 0 && s2[j-1] == s3[i+j-1] && dp[i][j-1]) {
                dp[i][j] = true;
            }
        }
    }
    
    return dp[m][n];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值