Leetcode Note: Interlaving String

Source: Internet
Author: User

Leetcode Note: Interlaving String

I. Description

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.

Ii. Question Analysis

This problem can be solved using two-dimensional dynamic planning. The following table shows the intuitive matching process:

Set the status of a gridk[i][j], Indicatess1[i]Ors2[j], Ands3[i+j].s3Ands1Ands2Matching can be divided into the following two situations:

Ifs1The last character of is equals3The last characterk[i][j]=k[i-1][j];
Ifs2The last character of is equals3The last characterk[i][j]=k[i][j-1].

Therefore, the state transition equation is as follows:
f[i][j] = (s1[i - 1] == s3 [i + j - 1] && f[i - 1][j]) "| (s2[j - 1] == s3 [i + j - 1] && f[i][j - 1]);

Iii. Sample Code

# Include
  
   
# Include
   
    
# Include
    
     
Using namespace std; class Solution {public: bool isInterleave (string s1, string s2, string s3) {if (s3.size ()! = S1.size () + s2.size () return false; if (s3 [0]! = S1 [0] & s3 [0]! = S2 [0]) return false; vector
     
      
> K (s1.size () + 1, vector
      
        (S2.size () + 1, false); k [0] [0] = true; // set the boundary for (size_t I = 1; I <= s1.size (); ++ I) k [I] [0] = (s1 [I-1] = s3 [I-1]) & k [I-1] [0]; for (size_t j = 1; j <= s2.size (); ++ j) k [0] [j] = (s2 [j-1] = s3 [j-1]) & k [0] [j-1]; for (size_t I = 1; I <= s1.size (); ++ I) {for (size_t j = 1; j <= s2.size (); ++ j) {k [I] [j] = (s1 [I-1] = s3 [I + j-1]) & k [I-1] [j]) | (s2 [j-1] = s3 [I + j-1]) & k [I] [j-1]);} return k [s1.size ()] [s2.size ()] ;}};
      
     
    
   
  

During programming, pay attention to the boundary condition and the array subscript.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.