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];
}
};
本文介绍了一种使用动态规划解决LeetCode上的Interleaving String问题的方法。该问题要求判断字符串s3是否能通过交替插入字符串s1和s2的字符形成。文章详细解释了动态规划的思路,并提供了一个高效的C++实现。

1万+

被折叠的 条评论
为什么被折叠?



