Interleaving String
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 =
s2 =
Given:
s1 =
"aabcc"
,s2 =
"dbbca"
,
When s3 =
When s3 =
"aadbbcbcac"
, return true.When s3 =
"aadbbbaccc"
, return false.------------------------------------- thinking ---------------------------------------
The below solution is beautiful!!!!!!
https://oj.leetcode.com/discuss/19973/8ms-c-solution-using-bfs-with-explanation
Please try to give some optimizations in the codes to reduce the usage of the memory
Ordinary DP solution
https://oj.leetcode.com/discuss/11694/my-dp-solution-in-c
-------------------------------------- codes ----------------------------------------------
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int len1 = s1.size();
int len2 = s2.size();
int len3 = s3.size();
if (len1+len2 != len3) {
return false;
}
bool dp[len1+1][len2+1];
memset(dp, false, sizeof(dp));
for(int i = 0; i < len1+1; i++) {
for (int j = 0; j < len2+1; j++) {
if (i==0 && j==0) {
dp[0][0] = true;
} else if (i==0) {
dp[0][j] = dp [0][j-1] && (s2[j-1] == s3[j-1]);
} else if (j==0) {
dp[i][0] = dp[i-1][0] && (s1[i-1] == s3[i-1]);
} else {
//bug here-> please be careful about the index, it should be s2[j-1] == s3[i+j-1]
//instead of s2[j] == s3[i+j] or s2[j-1] == s3[i+j-2]
dp[i][j] = (dp[i][j-1] && (s2[j-1] == s3[i+j-1])) ||
(dp[i-1][j] && (s1[i-1] == s3[i+j-1]));
}
}
}
return dp[len1][len2];
}
};
No comments:
Post a Comment