首页 > 代码库 > Leetcode: Interleaving String
Leetcode: Interleaving String
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.
分析:动态规划, f[i][j]表示s3[0:i+j-1]是s1[0:i-1]和s2[0:j-1]的interleaving string。递推公式如下:
f[i][j] = (s1[i-1] == s3[i+j-1]) && f[i-1][j] || (s2[j-1] == s3[i+j-1]) && f[i][j-1].
代码如下:
class Solution {public: bool isInterleave(string s1, string s2, string s3) { if (s3.length() != s1.length() + s2.length()) return false; vector<vector<bool>> f(s1.length() + 1,vector<bool>(s2.length() + 1, true)); for (size_t i = 1; i <= s1.length(); ++i) f[i][0] = f[i - 1][0] && s1[i - 1] == s3[i - 1]; for (size_t i = 1; i <= s2.length(); ++i) f[0][i] = f[0][i - 1] && s2[i - 1] == s3[i - 1]; for (size_t i = 1; i <= s1.length(); ++i) for (size_t j = 1; j <= s2.length(); ++j) f[i][j] = (s1[i - 1] == s3[i + j - 1] && f[i - 1][j]) || (s2[j - 1] == s3[i + j - 1] && f[i][j - 1]); return f[s1.length()][s2.length()]; }};
本题目的递推版本很容易理解,但超时。
Leetcode: Interleaving String
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。