leetcode: Interleaving String

本文介绍了一种使用动态规划解决字符串交错验证问题的方法。通过构建二维布尔数组,算法判断字符串s3是否能由s1和s2交错组成。文章详细解释了实现思路与步骤,并提供了完整的C++代码示例。

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

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.


这道题是我解决最有满足感的一到,到目前为止

开始的时候,从一维空间想,有点类似 贪心算法+回溯法的思想,看着简单,但是很多回溯是致错误的,然后加了很多if else,感觉这样的解法不应该是正确的

后来对问题抽象了一下,假设当前 s1的前n和元素和s2的前m个元素是满足interleaving了,那就可以判断s1[n+1]和s2[m]是不是满足 interleaving的条件,同时也可以判断s1[n]s2[m+1]是不是满足条件,这样采用动态规划的思想,最后可以判断出s1.size()s2.size()是不是可以满足条件


#define MAX_SIZE 101

class Solution {

bool table[MAX_SIZE][MAX_SIZE];
    
public:
    bool isInterleave(string s1, string s2, string s3) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        
        
    if (s1.size()+s2.size() != s3.size())
        return false;
        
        
    for (int i = 0; i< MAX_SIZE; i++)
    {
        for (int j = 0; j < MAX_SIZE; j++)
        {
            table[i][j] = false;
        }
    }
        
    table[0][0] = true;
        
    for (int i = 0; i < s1.size(); i++)
    {
        if (s1[i] == s3[i])
        {
            table[0][i+1] = true;
        }
    }
    
    for (int j = 0; j < s2.size(); j++)
    {
        if (s2[j] == s3[j])
        {
            table[j+1][0] = true;
        }
    }
    
    for (int i = 1; i <= s2.size(); i++)
    {
        for (int j = 1; j <= s1.size(); j++)
        {
            if (table[i-1][j] == true)
            {
                if (s3[i+j-1] == s2[i-1])
                {
                    table[i][j] = true;
                    continue;
                }
            }
            
            if (table[i][j-1] == true)
            {
                if (s3[i+j-1] == s1[j-1])
                {
                    table[i][j] = true;
                    continue;
                }
                
            }
        }
    }
    
    return table[s2.size()][s1.size()];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值