97. Interleaving String
LeetCode 97. Interleaving String
Description
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.
An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that:
s = s1 + s2 + ... + snt = t1 + t2 + ... + tm|n - m| <= 1The interleaving is
s1 + t1 + s2 + t2 + s3 + t3 + ...ort1 + s1 + t2 + s2 + t3 + s3 + ...
Note: a + b is the concatenation of strings a and b.
Example 1:

Example 2:
Example 3:
Constraints:
0 <= s1.length, s2.length <= 1000 <= s3.length <= 200s1,s2, ands3consist of lowercase English letters.
Follow up: Could you solve it using only O(s2.length) additional memory space?
Tags
String, Dynamic Programming
Solution
We use a 2D array dp where dp[i][j] represents if s3[:i+j] is formed by an interleaving of s1[:i] and s2[:j].
Edge cases:
Return false if
len(s1)+len(s2) != len(s3);dp[0][0] = truesince"" + "" == "".
In terms of s1, dp[i][j] = true if s1[i] == s3[i+j] and s3[:i-1+j] is formed by an interleaving of s1[:i-1] and s2[:j]. This is also similar to s2. Thus, we can derive a function from it:
At last, we return dp[len(s1)][len(s2)].
Now that we can observe that dp[i] only depends on dp[i-1], we can compress the len(s1)*len(s2) array to an 1D array with length of len(s2). See Code for details.
Complexity
Time complexity: ,
mandnare the length ofs1ands2, respectively;Space complexity:
Code
Reference
Last updated
Was this helpful?