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
题意
给出s1,s2,s3,判断是否能从s3中抽取出若干个字符以原顺序组成字符串和s1相等,并且s3剩下的部分正好组成了s2
题解
自然而然想到的dp,很慢
1 class Solution { 2 public: 3 bool isInterleave(string s1, string s2, string s3) { 4 int l1=s1.length(),l2=s2.length(),l3=s3.length(); 5 vector<vector<vector<bool>>>dp(l1+1,vector<vector<bool>>(l2+1,vector<bool>(l3+1,false))); 6 dp[0][0][0]=true; 7 for(int i=0;i<=l1;i++) 8 for(int j=0;j<=l2;j++){ 9 if(i>=1&&dp[i-1][j][i+j-1]&&s1[i-1]==s3[i+j-1]) 10 dp[i][j][i+j]=true; 11 else if(j>=1&&dp[i][j-1][i+j-1]&&s2[j-1]==s3[i+j-1]) 12 dp[i][j][i+j]=true; 13 } 14 return dp[l1][l2][l3]; 15 } 16 };
好吧,我是傻x
1 class Solution { 2 public: 3 bool isInterleave(string s1, string s2, string s3) { 4 int l1=s1.length(),l2=s2.length(),l3=s3.length(); 5 if(l1+l2!=l3)return false; 6 vector<vector<bool>>dp(l1+1,vector<bool>(l3+1,false)); 7 dp[0][0]=true; 8 for(int i=0;i<=l1;i++) 9 for(int j=0;j<=l2;j++){ 10 if(i>=1&&dp[i-1][i+j-1]&&s1[i-1]==s3[i+j-1]) 11 dp[i][i+j]=true; 12 else if(j>=1&&dp[i][i+j-1]&&s2[j-1]==s3[i+j-1]) 13 dp[i][i+j]=true; 14 } 15 return dp[l1][l3]; 16 } 17 };