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