LeetCode 97. Interleaving String

https://leetcode.com/problems/interleaving-string/

Description

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

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

Solution

动态规划裸题。解法见注释

class Solution:
    '''
    dp[i][j] means the first i characters of s1 and the first j characters of s2 can be combined to be s3.
    to handle the issue of index, I add '0' to each string, making that the index begins at 1 instead of 0.
    
    Simple derivation:
    if dp[i-1][j]==1 and s1[i]==s3[i+j], dp[i][j] = 1;
    if dp[i][j-1]==1 and s2[j]==s3[i+j], dp[i][j] = 1;
    else,m dp[i][j] = 0;
    '''
    def isInterleave(self, s1: 'str', s2: 'str', s3: 'str') -> 'bool':
        s1, s2, s3 = '0'+s1, '0'+s2, '0'+s3
        len1, len2, len3 = len(s1), len(s2), len(s3)
        dp = [[0 for i in range(len2)] for j in range(len1)]
        
        if len1+len2 != len3+1:
            return False
        # handle the empty string such as s1="", s2="", s3=""
        if len1 == 1:
            return s3 == s2
        if len2 == 1:
            return s3 == s1
        
        # initialize the dp array
        for i in range(1, len1):
            if s1[0:i+1] == s3[0:i+1]:
                dp[i][0] = 1
        for i in range(1, len2):
            if s2[0:i+1] == s3[0:i+1]:
                dp[0][i] = 1
        
        for i in range(1, len1):
            for j in range(1, len2):
                if dp[i-1][j] == 1 and s1[i] == s3[i+j]:
                    dp[i][j] = 1
                if dp[i][j-1] == 1 and s2[j] == s3[i+j]:
                    dp[i][j] = 1

        if dp[len1-1][len2-1] == 1:
            return True
        return False
        
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值