Medium
String
DP
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 s
and t
are divided into n
and m
substrings respectively, such that:
s = s1 + s2 + ... + sn
t = t1 + t2 + ... + tm
|n - m| <= 1
s1 + t1 + s2 + t2 + s3 + t3 + ...
or t1 + s1 + t2 + s2 + t3 + s3 + ...
Note: a + b
is the concatenation of strings a
and b
.
Example 1:
Example 2:
Example 3:
Constraints:
s1.length
, s2.length
<= 100s3.length
<= 200s1
, s2
, and s3
consist of lowercase English letters.Follow up: Could you solve it using only O(s2.length)
additional memory space?
dp[i][j]
表示 s1
的前 i
個字元和 s2
的前 j
個字元是否可以交錯組合成 s3
的前 i + j
個字元。
從下面兩個方向達到目前狀態 (i,j)
:
(i - 1, j)
轉移:
dp[i - 1][j] == true
,代表著 s1
的前 i - 1
個字元和 s2
的前 j
個字元可以交錯組合成 s3
的前 i + j - 1
個字元。s1[i - 1]
是否等於 s3[i + j - 1]
。如果相等,則 dp[i][j]
也為 true
i, j - 1
轉移:
dp[i, j - 1] == true
,代表著 s1
的前 i
個字元和 s2
的前 j - 1
個字元可以交錯組合成 s3
的前 i + j - 1
個字元。s2[j - 1]
是否等於 s3[i + j - 1]
。如果相等,則 dp[i][j]
也為 true
sheepFri, 25 Aug 2023
Yen-Chi ChenFri, Aug 25, 2023