leetcode@ [97] Interleaving Strings
https://leetcode.com/problems/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.
class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s1.length() + s2.length() != s3.length()) return false; if(s1.length() == 0 && s2.length() == 0 && s3.length() == 0) return true; vector<vector<bool> > dp(s1.length()+1, vector<bool>(s2.length()+1, false)); for(int i=1;i<=s1.length();++i) { dp[i][0] = (s1.substr(0,i) == s3.substr(0,i))? true: false; } for(int j=1;j<=s2.length();++j) { dp[0][j] = (s2.substr(0,j) == s3.substr(0,j))? true: false; } for(int i=1;i<=s1.length();++i) { for(int j=1;j<=s2.length();++j) { if(dp[i-1][j] && s1[i-1] == s3[i+j-1]) dp[i][j] = true; else if(dp[i][j-1] && s2[j-1] == s3[i+j-1]) dp[i][j] = true; else dp[i][j] = false; } } return dp[s1.length()][s2.length()]; } };