码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Interleaving String @ Python

时间:2014-06-06 07:26:08      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

原题地址:https://oj.leetcode.com/problems/interleaving-string/

题意:

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.

解题思路:动态规划。dp[i][j]表示s1[0...i-1]和s2[0...j-1]是否可以拼接为s3[0...i+j-1],可以拼接为true,不可以拼接为false。

代码:

bubuko.com,布布扣
class Solution:
    # @return a boolean
    def isInterleave(self, s1, s2, s3):
        if len(s1)+len(s2)!=len(s3): return False
        dp=[[False for i in range(len(s2)+1)] for j in range(len(s1)+1)]
        dp[0][0]=True
        for i in range(1,len(s1)+1):
            dp[i][0] = dp[i-1][0] and s3[i-1]==s1[i-1]
        for i in range(1,len(s2)+1):
            dp[0][i] = dp[0][i-1] and s3[i-1]==s2[i-1]
        for i in range(1,len(s1)+1):
            for j in range(1,len(s2)+1):
                dp[i][j] = (dp[i-1][j] and s1[i-1]==s3[i+j-1]) or (dp[i][j-1] and s2[j-1]==s3[i+j-1])
        return dp[len(s1)][len(s2)]
bubuko.com,布布扣

 

[leetcode]Interleaving String @ Python,布布扣,bubuko.com

[leetcode]Interleaving String @ Python

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3767650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!