Interleaving String, interleavingstring

Source: Internet
Author: User

Interleaving String, interleavingstring

GivenS1,S2,S3, Find whetherS3Is formed by the interleavingS1AndS2.

For example,
Given:
S1="aabcc",
S2="dbbca",

WhenS3="aadbbcbcac", Return true.
WhenS3="aadbbbaccc", Return false.

The simplest way of thinking is to do recursion, but this requires recursion at most s3 length layers, which consumes a lot and is prone to timeout errors. A timeout error occurs when performing recursive attempts, recursion is the most intuitive way to solve this problem.

Recursive method does not consider DP, we use path [I] [j] to record s1 to I and s2 to j and s3 [I + J-1] whether the requirements are met, this process is to fill in a two-dimensional array table. First initialize the first row and the first column, then fill in the table to calculate all, and return the value of path [s1.length] [s2.length.

AC code:

public class Solution {    public boolean isInterleave(String s1, String s2, String s3) {if(s1.length()+s2.length()!=s3.length()){return false;}int row = s1.length();int col = s2.length();boolean [][]path = new boolean[row+1][col+1];path[0][0] = true;for(int i=1;i<=row;i++){path[i][0] = path[i-1][0] && (s1.charAt(i-1)==s3.charAt(i-1));}for(int i=1;i<=col;i++){path[0][i] = path[0][i-1] && (s2.charAt(i-1) == s3.charAt(i-1));}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){path[i][j] = (path[i-1][j] && s1.charAt(i-1)==s3.charAt(i+j-1)) ||(path[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));}}return path[row][col];}}


 




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.