zoukankan      html  css  js  c++  java
  • LeetCode 97. Interleaving String

    原题链接在这里:https://leetcode.com/problems/interleaving-string/

    题目:

    Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

    Example 1:

    Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
    Output: true

    Example 2:

    Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
    Output: false

    题解:

    Let dp[i][j] denotes whether or not s1 till index i and s2 till index j could construct s3 till index i+j.

    If current index of s3 pointing to the char is equal to s1 current char, then || dp[i-1][j].

    If current index of s3 pointing to the char is equal to s2 current char, then || dp[i][j-1].

    Check finally dp[m][n] result.

    Note:

    current pointing index of s3 is i+j-1. It starts at 1, no need to worry about 0. It is already assigned before.

    Time Complexity: O(m*n). m = s1.length(). n = s2.length().

    Space: O(m*n).

    AC Java:

     1 class Solution {
     2     public boolean isInterleave(String s1, String s2, String s3) {
     3         int m = s1.length();
     4         int n = s2.length();
     5         if(m+n != s3.length()){
     6             return false;
     7         }
     8         
     9         boolean [][] dp = new boolean[m+1][n+1];
    10         dp[0][0] = true;
    11         for(int j = 1; j<=n; j++){
    12             if(s3.charAt(j-1) == s2.charAt(j-1)){
    13                 dp[0][j] = true;
    14             }else{
    15                 break;
    16             }
    17         }
    18         
    19         for(int i = 1; i<=m; i++){
    20             if(s3.charAt(i-1) == s1.charAt(i-1)){
    21                 dp[i][0] = true;
    22             }else{
    23                 break;
    24             }
    25         }
    26         
    27         for(int i = 1; i<=m; i++){
    28             for(int j = 1; j<=n; j++){
    29                 char c = s3.charAt(i+j-1);
    30                 if(c == s1.charAt(i-1)){
    31                     dp[i][j] = dp[i][j] | dp[i-1][j];
    32                 }
    33                 
    34                 if(c == s2.charAt(j-1)){
    35                     dp[i][j] = dp[i][j] | dp[i][j-1];
    36                 }
    37             }
    38         }
    39         
    40         return dp[m][n];
    41     }
    42 }

    类似Edit Distance.

  • 相关阅读:
    SQL语句熟悉
    CSS3 attribute
    轮播器
    PHP 邮箱操作的Action
    Hole puncher Show Picture
    力扣算法——133.CloneGraph【M】
    力扣算法——134GasStation【M】
    力扣算法——135Candy【H】
    力扣算法——136SingleNumber【E】
    力扣算法——137SingleNumberII【M】
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824939.html
Copyright © 2011-2022 走看看