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.
采用动态规划,假设dp[i][j]表示了s1的前i个元素(包括第i个元素)s1[1],s1[2].....s1[i-1],与s2的前j个元素(包括第j个元素)s2[1],s2[2]...s2[j-1]是否可以构成s3
有两种情况可以考虑,
如果dp[i-1][j]成立了,且s1[i-1]==s3[i+j-1],那么可以认为dp[i][j]成立
如果dp[i][j-1]成立了,且s2[j-1]==s3[i+j-1],也可以认为dp[i][j]成立
所以可以得到如下的递推式:
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]);
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 };
时间: 2024-10-11 07:27:55