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:
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:
- 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 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