zoukankan      html  css  js  c++  java
  • 【leetcode】97. Interleaving String

    题目如下:

    解题思路:本题可以采用动态规划的方法。记dp[i][j]表示用s1的前i个字符和s2的前j个字符能否组成s3的前(i+j)个字符,如果dp[i-1][j]是True的话,只要s1[i] == s3[i-1+j],那么dp[i][j]就为True;同理,如果dp[i][j-1]是True,只要满足s2[j] == s3[i-1+j],那么dp[i][j]也为True。

    代码如下:

    class Solution(object):
        def isInterleave(self, s1, s2, s3):
            """
            :type s1: str
            :type s2: str
            :type s3: str
            :rtype: bool
            """
            if len(s1) + len(s2) == 0:
                return len(s3) == 0
            elif len(s1) == 0:
                return s2 == s3
            elif len(s2) == 0:
                return s1 == s3
            elif len(s1) + len(s2) != len(s3):
                return False
    
            dp = [ [0]* (len(s2) + 1)  for i in range(len(s1)+1) ]
            if s1[0] == s3[0]:
                dp[1][0] = 1
            if s2[0] == s3[0]:
                dp[0][1] = 1
    
            for i in range(len(dp)):
                for j in range(len(dp[i])):
                    if i > 0 and j > 0 and dp[i-1][j] == 0 and dp[i][j-1] == 0:
                        dp[i][j] = 0
                    elif i > 0 and dp[i-1][j] == 1 and s1[i-1] == s3[i-1+j]:
                        dp[i][j] = 1
                    elif j > 0 and dp[i][j-1] == 1 and s2[j-1] == s3[i+j-1]:
                        dp[i][j] = 1
            #print dp
            return dp[-1][-1] == 1
  • 相关阅读:
    实验 7 综合练习一
    实验或作业模版: 实验 6-1 最大公约数 最小公倍数
    实验 6 数组1
    Pro
    作业 4 函数应用
    老大
    双端队列
    zxa and leaf
    Baby Ming and Matrix games
    The more, The Better
  • 原文地址:https://www.cnblogs.com/seyjs/p/9556458.html
Copyright © 2011-2022 走看看