class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s1.size() + s2.size() != s3.size())
{
return false;
}
//二维动态规划, f[i][j]表示s3的前i + j个字符是否可由s1的前i个字符和s2的前j个字符组成
//则以下任一种情况成立,f[i][j]为真,否则为假
//1.s3的前i+j-1个字符可由s1的前i-1个字符以及s2的前j个字符组成,且s3[i+j-1]==s1[i-1]
//2.s3的前i+j-1个字符可由s1的前i个字符以及s2的前j-1个字符组成,且s3[i+j-1]==s2[j-1]
bool f[1000][1000];
f[0][0] = true;
for (size_t i = 1; i <= s1.size(); ++i)
{
f[i][0] = f[i - 1][0] && s1[i - 1] == s3[i - 1];
}
for (size_t j = 1; j <= s2.size(); ++j)
{
f[0][j] = f[0][j - 1] && s2[j - 1] == s3[j - 1];
}
for (size_t i = 1; i <= s1.size(); ++i)
{
for (size_t j = 1; j <= s2.size(); ++j)
{
f[i][j] = f[i - 1][j] && s1[i - 1] == s3[i + j - 1]
|| f[i][j - 1] && s2[j - 1] == s3[i + j - 1];
}
}
return f[s1.size()][s2.size()];
}
};
LeetCode-Interleaving String
最新推荐文章于 2024-11-09 21:51:15 发布