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.
动态规划,前i个s1和前j个s2能否组成前i+j
class Solution { public: bool isInterleave(string s1, string s2, string s3) { // Note: The Solution object is instantiated only once and is reused by each test case. if(s1.length()+s2.length()!=s3.length()){ return false; } vector<vector<bool> > m; vector<bool> one; one.resize(s2.length()+1,false); m.resize(s1.length()+1,one); m[0][0]=true; bool flag=true; for(int i=1;i<=s1.length();i++){ if(s1[i-1]==s3[i-1]){ if(flag)m[i][0]=true; } else{ flag=false; } } flag=true; for(int i=1;i<=s2.length();i++){ if(s2[i-1]==s3[i-1]){ if(flag)m[0][i]=true; } else{ flag=false; } } for(int i=1;i<=s1.length();i++){ for(int j=1;j<=s2.length();j++){ if(s3[i+j-1]==s1[i-1]&&m[i-1][j]){ m[i][j]=true; continue; } if(s3[i+j-1]==s2[j-1]&&m[i][j-1]){ m[i][j]=true; } } } return m[s1.length()][s2.length()]; } };