leetcode : Interleaving String(DFS 和 DP)

来源:互联网 发布:不一样的卡梅拉 知乎 编辑:程序博客网 时间:2024/05/22 00:08

Interleaving String

 Total Accepted: 21379 Total Submissions: 107884My Submissions

Given s1s2s3, 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.


这个题目可以使用深度优先搜索和动态规划来解决,先贴一下DFS的代码(使用深度优先搜索会超时):

bool dfs(const string& s1, const string& s2,string& s3, size_t idx1, size_t idx2){if (idx1 == s1.size() && idx2 == s2.size())return true;if (idx1 > s1.size() || idx2 > s2.size())return false;if (s1[idx1] != s3[idx1 + idx2] && s2[idx2] != s3[idx1 + idx2])return false;if (s1[idx1] == s3[idx1 + idx2] && dfs(s1, s2, s3, idx1 + 1, idx2))return true;if (s2[idx2] == s3[idx1 + idx2] && dfs(s1, s2, s3, idx1, idx2 + 1))return true;return false;}bool isInterleave(string s1, string s2, string s3) {if (s1.size() + s2.size() != s3.size())return false;bool ret = dfs(s1, s2, s3, 0, 0);return ret;}

下面附上使用动态规划的代码:dp[i][j]表示s1的前i个字符和s2的前j个字符可以组成s3的前i+j个字符。

bool isInterleave(string s1, string s2, string s3) {if (s1.size() + s2.size() != s3.size())return false;vector<vector<bool> > dp(s1.size()+1, vector<bool>(s2.size()+1, false));dp[0][0] = true;for (size_t i = 1; i <= s1.size(); ++i){dp[i][0] = (s1[i-1] == s3[i-1] );}for (size_t j = 1; j <= s2.size(); ++j){dp[0][j] = (s2[j-1] == s3[j-1]);}for (size_t i = 1; i <= s1.size(); ++i){for (size_t j = 1; j <= s2.size(); ++j){if (dp[i][j - 1] && s2[j-1] == s3[i + j - 1])dp[i][j] = true;else if (dp[i - 1][j] && s1[i-1] == s3[i + j - 1])dp[i][j] = true;elsedp[i][j] = false;}}return dp[s1.size()][s2.size()];}



0 0