LeetCode Interleaving String

Source: Internet
Author: User

LeetCode Interleaving String

 

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.

Question: Can the s1 and s2 strings be combined into S3.

Idea: DP is done. dp [I + 1] [j + 1] indicates s1 [0... i] and s2 [0... j] whether it can be combined into s3 [I + j + 1]. When dp [I] [j + 1] is true, if s1 [I + 1] = s3 [I + j + 1], dp [I + 1] [j + 1] will meet the requirements, the same is true for dp [I + 1] [j.

 

 

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


 

 

 

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.