标签:pre blog vector ane adb int min and rmi
题目:
Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
For s1 = "aabcc"
, s2 = "dbbca"
"aadbbcbcac"
, return true
."aadbbbaccc"
, return false
.题解:
Solution 1 ()
class Solution { public: bool isInterleave(string s1, string s2, string s3) { int n1 = s1.size(), n2 = s2.size(), n3 = s3.size(); if (n1 + n2 != n3) { return false; } vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, false)); dp[0][0] = true; for (int i = 1; i <= n1; ++i) { dp[i][0] = dp[i - 1][0] && (s1[i - 1] == s3[i - 1]); } for (int i = 1; i <= n2; ++i) { dp[0][i] = dp[0][i - 1] && (s2[i - 1] == s3[i - 1]); } for (int i = 1; i <= n1; ++i) { for (int j = 1; j <= n2; ++j) { dp[i][j] = (dp[i - 1][j] && s1[i - 1] == s3[i - 1 + j]) || (dp[i][j - 1] && s2[j - 1] == s3[j - 1 + i]); } } return dp[n1][n2]; } };
Solution 2 ()
class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s1.length() + s2.length() != s3.length()) return false; bool dp[s2.length() + 1]; for(int i = 0; i <= s1.length(); i++){ for(int j = 0; j <= s2.length(); j++){ if(i == 0 && j == 0) dp[j] = true; else if(i == 0) dp[j] = (dp[j - 1] && s3[i + j - 1] == s2[j - 1]); else if(j == 0) dp[j] = (dp[j] && s3[i + j - 1] == s1[i - 1]); else dp[j] = (dp[j] && s3[i + j - 1] == s1[i - 1]) || (dp[j - 1] && s3[i + j - 1] == s2[j - 1]); } } return dp[s2.length()]; } };
DFS
Solution 3 ()
BFS
Solution 4 ()
【Lintcode】029.Interleaving String
标签:pre blog vector ane adb int min and rmi
原文地址:http://www.cnblogs.com/Atanisi/p/6884025.html