[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.
动态规划,类似于求最长公共子序列。
1 class Solution { 2 public: 3 bool isInterleave(string s1, string s2, string s3) { 4 if (s1.size() + s2.size() != s3.size()) { 5 return false; 6 } 7 8 bool a[1000][1000]; 9 a[0][0] = true; 10 for (int i = 1; i <= s1.size(); ++i) { 11 a[i][0] = a[i-1][0] && (s1[i-1] == s3[i-1]); 12 } 13 for (int i = 1; i <= s2.size(); ++i) { 14 a[0][i] = a[0][i-1] && (s2[i-1] == s3[i-1]); 15 } 16 for (int i = 1; i <= s1.size(); ++i) { 17 for (int j = 1; j <= s2.size(); ++j) { 18 a[i][j] = (a[i-1][j] && s1[i-1] == s3[i+j-1]) || (a[i][j-1] && s2[j-1] == s3[i+j-1]); 19 } 20 } 21 return a[s1.size()][s2.size()]; 22 } 23 };