[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.
DP.
1 class Solution { 2 private: 3 bool f[1000][1000]; 4 public: 5 bool isInterleave(string s1, string s2, string s3) { 6 // Start typing your C/C++ solution below 7 // DO NOT write int main() function 8 if (s1.size() + s2.size() != s3.size()) 9 return false; 10 11 f[0][0] = true; 12 for(int i = 1; i <= s1.size(); i++) 13 f[i][0] = f[i-1][0] && (s3[i-1] == s1[i-1]); 14 15 for(int j = 1; j <= s2.size(); j++) 16 f[0][j] = f[0][j-1] && (s3[j-1] == s2[j-1]); 17 18 for(int i = 1; i <= s1.size(); i++) 19 for(int j = 1; j <= s2.size(); j++) 20 f[i][j] = (f[i][j-1] && s2[j-1] == s3[i+j-1]) || (f[i-1][j] && s1[i-1] == s3[i+j-1]); 21 22 return f[s1.size()][s2.size()]; 23 } 24 };