码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 97. Interleaving String_ Hard tag: Dynamic Programming

时间:2019-04-29 12:33:45      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:style   str   whether   for   false   als   min   char   lse   

Given s1s2s3, 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
 
这个题目利用dynamic programming,mem[l1 + 1][l2 + 1]  #mem[i][j] means that whether the first i characters of s1 and the first j characters of s2 be able to make first i + j characters of s3. 
  mem[i][j] = (mem[i - 1][j] and s1[i - 1] == s3[i + j - 1])   # when the last character of s3 matches the last of s1
          or (mem[i][j - 1]) and s2[j - 1] == s3[i + j - 1])  # when the last character of s3 matches the last of s2
     initial: mem[i][0] = s1[:i] == s3[:i]
      mem[0][j] = s2[:j] == s3[:j]
 
code
class Solution:
    def interLeaveString(self, s1, s2, s3):
            l1, l2, l3 = len(s1), len(s2), len(s3)
            if l1 + l2 != l3: return False
            mem = [[False] * (l2 + 1) for _ in range(l1 + 1)]
            for i in range(l1 + 1):
                mem[i][0] = s1[:i] == s3[:i]
            for j in range(l2 + 1):
                mem[0][j] = s2[:j] == s3[:j]
            for i in range(1, 1 + l1):
                for j in range(1, 1 + l2):
                    mem[i][j] = (mem[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (mem[i][j - 1] and s2[j - 1] == s3[i + j - 1])
            return mem[l1][l2]

 

 

[LeetCode] 97. Interleaving String_ Hard tag: Dynamic Programming

标签:style   str   whether   for   false   als   min   char   lse   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/10789615.html

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