3/04/2013

Interleaving String

Interleaving StringAug 31 '12
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.
dp[i][j] == true means the substring of s3 from start to 'i + j'th char is the interleaved string of s2 till 'i'th char and s1 till 'j'th char

  1. class Solution {
  2. public:
  3. bool isInterleave(string s1, string s2, string s3) {
  4. // Start typing your C/C++ solution below
  5. // DO NOT write int main() function
  6. if (s1.empty()) return s2 == s3;
  7. else if (s2.empty()) return s1 == s3;
  8. else if (s3.empty()) return s1.empty() && s2.empty();
  9. else if (s1.size() + s2.size() != s3.size()) return false;
  10. int lengthS1 = s1.size() + 1, lengthS2 = s2.size() + 1;
  11. vector<vector<bool>> dp(lengthS2, vector<bool>(lengthS1, false));
  12. dp[0][0] = true;
  13. for (int i = 1; i < lengthS2; ++i) {
  14. dp[i][0] = s2[i - 1] == s3[i - 1] ? dp[i - 1][0] : false;
  15. }
  16. for (int j = 1; j < lengthS1; ++j) {
  17. dp[0][j] = s1[j - 1] == s3[j - 1] ? dp[0][j - 1] : false;
  18. }
  19. for (int i = 1; i < lengthS2; ++i) {
  20. for (int j = 1; j < lengthS1; ++j) {
  21. if (s1[j - 1] == s3[i + j - 1]) {
  22. dp[i][j] = dp[i][j] || dp[i][j - 1];
  23. }
  24. if (s2[i - 1] == s3[i + j - 1]) {
  25. dp[i][j] = dp[i][j] || dp[i - 1][j];
  26. }
  27. }
  28. }
  29. return dp[lengthS2 - 1][lengthS1 - 1];
  30. }
  31. };

No comments:

Post a Comment