Leetcode: Interleaving String

来源:互联网 发布:太极软件 政务 编辑:程序博客网 时间:2024/05/16 23:43

Question

Given s1, s2, s3, 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.

Show Tags


The first try

class Solution(object):    def isInterleave(self, s1, s2, s3):        """        :type s1: str        :type s2: str        :type s3: str        :rtype: bool        """        if len(s3)!=(len(s1)+len(s2)):            return False        if len(s1)==0:            return True if s2==s3 else False        if len(s2)==0:            return True if s1==s3 else False        i, j, k = 0, 0, 0         while i<len(s1) and j<len(s2):            if s3[k]==s1[i]:                i += 1            elif s3[k]==s2[j]:                j += 1            else:                return False            k += 1        return True

Wrong case

Input:     "aa", "ab", "abaa"Output:    falseExpected:  true

Solution

Get idea from here.
To solve the problem in last section, a res list is created to record whether the first i elems of s1 and the first elems of s2 ( res[i][j] ) could interleave s3. It also optimized to a one dimension list.

Code

class Solution(object):    def isInterleave(self, s1, s2, s3):        """        :type s1: str        :type s2: str        :type s3: str        :rtype: bool        """        if len(s3)!=(len(s1)+len(s2)):            return False        mins = s1 if len(s1)<=len(s2) else s2        maxs = s1 if len(s1)>len(s2) else s2        res = [False]*(len(mins)+1)        res[0] = True        for ind in range(len(mins)):            res[ind+1] = res[ind] and mins[ind]==s3[ind]        for hind in range(len(maxs)):            res[0] = res[0] and maxs[hind]==s3[hind]            for vind in range(len(mins)):                res[vind+1] = (res[vind+1] and maxs[hind]==s3[hind+vind+1]) or (res[vind] and mins[vind]==s3[hind+vind+1])        return res[-1]
0 0