Interleaving String - LeetCode
2017-12-07 14:21
309 查看
Interleaving String - LeetCode
题目:Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = “aabcc”,
s2 = “dbbca”,
When s3 = “aadbbcbcac”, return true.
When s3 = “aadbbbaccc”, return false.
动态规划的题目
想法是用一个数组a[k][i][j]记录
s3的前k个字符能否由
s1的前i个字符与
s2的前j个字符插成
注意这里可以降低一个维度,因为i+j=k,所以用a[k][i]就够了。
递推关系式
a[k][i] = (a[k-1][i-1]&&s1[i-1]==s3[k-1]) || (a[k-1][i]&&s2[k-i-1]==s3[k-1])
注意这里推导
a[k][i]只用了
a[k-1][i]与
a[k-1][i-1](上面一格与左上一格),所以如果我们在计算时按从右往左顺序,就可以再降低一个维度。
上代码
class Solution { public: bool isInterleave(string s1, string s2, string s3) { int l1,l2,l3; l1 = s1.length(); l2 = s2.length(); l3 = s3.length(); if (l3 != l1+l2) return false; vector<bool> dp(l1+1, false); dp[0] = true; for (int i = 1; i <= l3; i++) { int t = min(l1, i); for (int j = t; j >= 0; j--) { bool a = false, b = false; if (dp[j] == 1 && s2[i-j-1] == s3[i-1]) a = true; if (j > 0 && dp[j-1] == 1 && s1[j-1] == s3[i-1]) b = true; dp[j] = a || b; } } return dp[l1]; 8c77 } };
相关文章推荐
- [leetcode刷题系列]Interleaving String
- LeetCode:Interleaving String
- [leetcode] 97.Interleaving String
- leetcode -- Interleaving String
- LeetCode 55 Interleaving String
- Leetcode 97. Interleaving String
- LeetCode-Interleaving String
- LeetCode: Interleaving String
- [LeetCode]97.Interleaving String
- LeetCode "Interleaving String"
- [LeetCode]Interleaving String
- Leetcode | Interleaving String
- [LeetCode] Interleaving String
- [leetcode]Interleaving String
- leetcode - Interleaving String
- Leetcode--Interleaving String
- LeetCode_Interleaving String
- 【LeetCode】Interleaving String && CSDN 交替字符串
- [LeetCode] 037: Interleaving String
- leetcode:Interleaving String 使用动态规划求解的java源代码