标签:
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 5 int n1=s1.length(); 6 int n2=s2.length(); 7 int n3=s3.length(); 8 9 if(n1+n2!=n3) 10 { 11 return false; 12 } 13 14 vector<vector<bool> > dp(n1+1,vector<bool>(n2+1,false)); 15 16 dp[0][0]=true; 17 18 for(int i=1;i<=n1;i++) 19 { 20 dp[i][0]=dp[i-1][0]&&s1[i-1]==s3[i-1]; 21 } 22 23 for(int j=1;j<=n2;j++) 24 { 25 dp[0][j]=dp[0][j-1]&&s2[j-1]==s3[j-1]; 26 } 27 28 for(int i=1;i<=n1;i++) 29 { 30 for(int j=1;j<=n2;j++) 31 { 32 dp[i][j]=(dp[i-1][j]&&s1[i-1]==s3[i+j-1])||(dp[i][j-1]&&s2[j-1]==s3[i+j-1]); 33 } 34 } 35 36 return dp[n1][n2]; 37 } 38 };
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4185784.html