Leetcode interleaving String

Source: Internet
Author: User

Leetcode Problem Solving interleaving string original problem

Enter three strings S1, S2, and S3 to determine whether the third string S3 is alternating from the first two strings S1 and S2 and does not change the relative order of the characters in S1 and S2.

Note the point:

    • No

Example:

Input: S1 = "AABCC", s2 = "DBBCA", s3 = "AADBBCBCAC"

Output: True

Thinking of solving problems

A typical two-dimensional dynamic programming topic, DP[I][J] indicates whether s1[:i+1] and s2[:j+1] can be alternately composed of s3[:i+j+1], two empty strings may form an empty string, so dp[0][0] is true. The condition of the boundary is that one string is empty and the other string has the same head as the target string's avatar. In general, Dp[i][j] is true only when one of the following two cases is established:

    1. S1[i] = = S3[i+j], and Dp[i-1][j] is true
    2. 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 the data between different latitudes does not interfere, all can reduce the two-dimensional DP to one-dimensional.

AC Source
 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)ifM + N! = L:return FalseDP = [True  for__inchRange (M +1)] forIinchRange (m): Dp[i +1] = Dp[i] andS1[i] = = S3[i] forJinchRange (n): dp[0] = dp[0] andS2[J] = = S3[j] forIinchRange (m): Dp[i +1] = (Dp[i] andS1[i] = = S3[i + j +1])or(Dp[i +1] andS2[J] = = S3[i + j +1])returnDP[M]if__name__ = ="__main__":assertSolution (). Isinterleave ("AABCC","DBBCA","AADBBCBCAC") ==True    assertSolution (). Isinterleave ("AABCC","DBBCA","AADBBBACCC") ==False

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

Leetcode interleaving String

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.