[Leedcode 97] Interleaving String

Source: Internet
Author: User

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.

 Public classSolution { Public BooleanIsinterleave (string s1, String s2, string s3) {//Dynamic programming idea, constructs a two-dimensional array, Dp[i][j] Indicates whether the S1 of the first I bit and S2 of the first J-bit meet the requirements//The state transition equation is dp[i][j]= (Dp[i-1][j]&&s1.charat (i-1) ==s3.charat (i+j-1)) | |        (Dp[i][j-1]&&s2.charat (j-1) ==s3.charat (i+j-1)); //attention to the subscript problem, the size of DP is [len1+1][len2+1], Dp[0][j] represents 0 S1 characters and J S2 characters to meet the requirements of a string        intlen1=s1.length (); intLen2=s2.length (); intlen3=s3.length (); if(LEN1+LEN2!=LEN3)return false; Booleandp[][]=New Boolean[Len1+1] [Len2+1]; dp[0][0]=true;  for(inti=1;i<=len1;i++) {dp[i][0]=dp[i-1][0]&&s1.charat (i-1) ==s3.charat (i-1); }         for(intj=1;j<=len2;j++) {dp[0][j]=dp[0][j-1]&&s2.charat (j-1) ==s3.charat (j-1); }         for(inti=1;i<=len1;i++){             for(intj=1;j<=len2;j++) {Dp[i][j]= (Dp[i-1][j]&&s1.charat (i-1) ==s3.charat (i+j-1)) | | (Dp[i][j-1]&&s2.charat (j-1) ==s3.charat (i+j-1)); }        }        returnDp[len1][len2]; }}

[Leedcode 97] Interleaving String

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.