# 19.2.27 [LeetCode 97] Interleaving String

Given s1s2s3, 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

## 题解

 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 };
View Code

 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 };
View Code

posted @ 2019-02-27 20:15  TobicYAL  阅读(139)  评论(0编辑  收藏  举报