97. Interleaving String
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
Approach #1: DP. [C++]
class Solution { public: bool isInterleave(string s1, string s2, string s3) { //if (s1 == "" && s2 == "" && s3 == "") return true; //if (s1 == "" || s2 == "" || s3 == "") return false; if (s1.length() + s2.length() != s3.length()) return false; vector<vector<bool>> match(s1.length()+1, vector<bool>(s2.length()+1, false)); match[0][0] = true; for (int idx = 0; idx < s1.length() + s2.length(); ++idx) { for (int s1Len = 0; s1Len <= idx+1 && s1Len <= s1.length(); ++s1Len) { int s2Len = idx + 1 - s1Len; if (s2Len > s2.length()) continue; if ((s1Len > 0 && match[s1Len-1][s2Len] && s3[idx] == s1[s1Len-1]) || (s2Len > 0 && match[s1Len][s2Len-1] && s3[idx] == s2[s2Len-1])) match[s1Len][s2Len] = true; } } return match[s1.length()][s2.length()]; } };
Analysis:
status: match[s1Len][s2Len] represent s1Len characters in s1 and s2Len characters in s2 wether match with s1Len+s2Len characters in s3.
init: match[0][0] = true;
func:
result: match[s1.length()][s2.length()].
永远渴望,大智若愚(stay hungry, stay foolish)