"Leetcode" interleaving String

Source: Internet
Author: User

Interleaving String

Given s1, S2, S3, find whether S3 are 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.

It can be done recursively, with each match S1 or S2 in a recursive way. But it will time out.

So consider doing it with dynamic planning.

S1, S2 has only two strings, so it can be flattened into a two-dimensional map to determine if it can go from the upper-left corner to the lower-right corner.

When the S1 arrives at the element I, S2 arrives at the first J element:

On the map, the right step is s2[j-1] match s3[i+j-1].

The next step on the map is s1[i-1] Match s3[i+j-1].

Example: s1= "AA", s2= "AB", s3= "Aaba". The standard 1 is feasible. Finally, return to the lower right corner.

0 A B

0 1 1 0

A 1 1 1

A 1 0 1

classSolution { Public:    BOOLIsinterleave (stringS1,stringS2,stringS3) {        if(S1.size () +s2.size ()! =s3.size ())return false; //s1.size () +1 by s2.size () +1 matrix representing pathvector<vector<BOOL> > Path (s1.size () +1, vector<BOOL> (s2.size () +1,false)); path[0][0] =true;  for(inti =0; I < s1.size () +1; i + +)        {//Row             for(intj =0; J < S2.size () +1; J + +)            {//Col                if(i = =0&& J = =0)                //Start                    ; Else if(i = =0)                //Go by S2PATH[I][J] = path[i][j-1] && (s2[j-1] = = s3[j-1]); Else if(J = =0)                //go by S1PATH[I][J] = path[i-1][J] && (s1[i-1] = = s3[i-1]); ElsePath[i][j]= (path[i][j-1] && (s2[j-1] = = s3[i+j-1])) || (path[i-1][J] && (s1[i-1] = = s3[i+j-1])); }        }        returnpath[s1.size ()][s2.size ()]; }};

"Leetcode" interleaving String

Related Article

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.