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
  • 相关阅读:
    Boost练习程序(强制转换)
    4873279(1002)
    A+B Problem(1000)
    STL练习程序(去除相同元素)
    Boost练习程序(智能指针)
    Sql技巧总结
    MySql Show Status详解
    mysql show status调优
    mysql decimal、numeric数据类型
    Apache Thrift学习小记
  • 原文地址:https://www.cnblogs.com/seyjs/p/9556458.html
Copyright © 2011-2022 走看看