英文原题
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 + … + sn t = t1 + t2 + … + tm |n - m| <= 1 The interleaving is 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
分析
又是一道动态规划,刚拿到题目我还没想到用动态规划,也是看了别人的思路才会做的。这是一道二维的动态规划,dp[i][j]表示s1前i个加上s2前j个是否可以组成s3的前i+j个。起初我在交错这个点上困住了,其实解法并不需要刻意去考虑交错的问题,因为其实两个字符串拆开排下来肯定是交错的。
python 代码
1 | class Solution: |