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.
动态规划!
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// The length of s3 should be the sum of length of s1 and s2.
if (s1.length() + s2.length() != s3.length())
return false;
vector<vector<bool> > table(s1.length() + 1, vector<bool>(s2.length() + 1, false));
// Initialize the table for 动态规划
table[0][0] = true;
for(int ii = 1; ii <= s1.length(); ii++)
table[ii][0] = table[ii-1][0] && (s3[ii-1] == s1[ii-1]);
for(int jj = 1; jj <= s2.length(); jj++)
table[0][jj] = table[0][jj-1] && (s3[jj-1] == s2[jj-1]);
for(int ii = 1; ii <= s1.length(); ii ++)
for(int jj = 1; jj <= s2.length(); jj ++)
table[ii][jj] = (table[ii][jj - 1] && s2[jj - 1] == s3[ii + jj - 1]) || (table[ii - 1][jj] && s1[ii-1] == s3[ii + jj - 1]);
return table[s1.length()][s2.length()];
}
};
本文介绍了一种使用动态规划解决字符串交错问题的方法。该方法通过构建一个二维布尔表来记录两个输入字符串是否能交错形成目标字符串。文章提供了一个C++实现示例,并详细解释了其工作原理。
779

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



