LeetCode Interleaving String

Source: Internet
Author: User

LeetCode Interleaving String
LeetCode-related Interleaving String

Original question

Enter three strings s1, s2, and s3 to determine whether the third string s3 is composed of the first two strings s1 and s2, without changing the original relative sequence of each character in s1 and s2.

Note:

None

Example:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"

Output: True

Solutions

For typical two-dimensional dynamic planning questions, dp [I] [j] indicates whether s1 [: I + 1] and s2 [: j + 1] can form s3 [: I + j + 1], two empty strings can constitute an empty string, so dp [0] [0] is True. The boundary condition is whether the header of a string is the same as that of the target string. In general, dp [I] [j] is True only when the following two conditions are met:

S1 [I] = s3 [I + j], and dp [I-1] [j] is True s2 [j] = s3 [I + j], and dp [I] [J-1] is True

The recursive relationship is:dp[i + 1][j + 1] = (dp[j + 1][i] and s1[i] == s3[i + j + 1]) or (dp[j][i + 1] and s2[j] == s3[i + j + 1])

Considering that data at different latitudes does not interfere with each other, two-dimensional dp can be reduced to one-dimensional.

AC Source Code
class Solution(object):    def isInterleave(self, s1, s2, s3):        """        :type s1: str        :type s2: str        :type s3: str        :rtype: bool        """        m = len(s1)        n = len(s2)        l = len(s3)        if m + n != l:            return False        dp = [True for __ in range(m + 1)]        for i in range(m):            dp[i + 1] = dp[i] and s1[i] == s3[i]        for j in range(n):            dp[0] = dp[0] and s2[j] == s3[j]            for i in range(m):                dp[i + 1] = (dp[i] and s1[i] == s3[i + j + 1]) or (dp[i + 1] and s2[j] == s3[i + j + 1])        return dp[m]if __name__ == "__main__":    assert Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac") == True    assert Solution().isInterleave("aabcc", "dbbca", "aadbbbaccc") == False

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.