动态规划 交叉字符串

给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。


您在真实的面试中是否遇到过这个题?
样例

比如 s1 = "aabcc" s2 = "dbbca"

    - 当 s3 = "aadbbcbcac",返回  true.

    - 当 s3 = "aadbbbaccc", 返回 false.


这是一道匹配的问题,我们用一个二维数组来存储s1和s2分别在s3中匹配的程度:

如:

match[i][j]表示s1字符串匹配到第i个字符,s2匹配到第j个字符

还有剩下的小问题就是一些索引的范围问题了,一定要注意每个字符串中索引的取值范围

贴代码:

class Solution:
    """
    @param s1: A string
    @param s2: A string
    @param s3: A string
    @return: Determine whether s3 is formed by interleaving of s1 and s2
    """
    def isInterleave(self, s1, s2, s3):
        # write your code here
        l1 = len(s1)
        l2 = len(s2)
        l3 = len(s3)
        match = [[False for i in range(l2+1)] for j in range(l1+1)]
        match[0][0] = True
        
        if l1+l2 != l3:
            return False
        
        for i in range(1,l1+1):
            if s1[i-1]==s3[i-1]:
                match[i][0] = True
        
        for i in range(1, l2+1):
            if s2[i-1] == s3[i-1]:
                match[0][i] = True
            
        for i in range(1,l1+1):
            for j in range(1,l2+1):
                k = i+j
                if s1[i-1]==s3[k-1]:
                    match[i][j] = match[i][j] or match[i-1][j]
                if s2[j-1]==s3[k-1]:
                    match[i][j]=match[i][j] or match[i][j-1]
                
        return match[l1][l2]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值