• 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.

    Analysis:

    Initially, we consider the state d[k,i,j] as whether the first k chars in s3 is the interleaving string of the first i chars of s1 and the first j chars of s2. We then have the formula:

    d[k,i,j] = d[k-1][i-1][j] && s3[k]==s1[i]  || d[k-1][i][j-1] && s3[k]==s2[j].

    We then find that since a state d[k,i,j] has meaning only when k==(i+j), we actaully can reduce the number of states. We further use the state d[i,j] to present whether the s1[0-(i-1)] and s2[0-(j-1)] can interleave to s3[0-(i+j-1)]. we have formula:

    d[i][j] = d[i-1][j] && s3[i+j-1]==s1[i-1]    ||   d[i][j-1] && s3[i+j-1]==s2[j-1].

    Solution:

     1 public class Solution {
     2     public boolean isInterleave(String s1, String s2, String s3) {
     3         int len1 = s1.length();
     4         int len2 = s2.length();
     5         
     6         //NOTE: need to consider this boundary case!
     7         if (s3.length()!=len1+len2) return false;
     8         
     9         boolean[][] d = new boolean[len1+1][len2+1];
    10         d[0][0]=true;
    11         for (int i=1;i<=len2;i++)
    12             if (d[0][i-1] && s2.charAt(i-1)==s3.charAt(i-1))
    13                 d[0][i]=true;
    14             else d[0][i]=false;
    15 
    16         for (int i=1;i<=len1;i++)
    17             if (d[i-1][0] && s1.charAt(i-1)==s3.charAt(i-1))
    18                 d[i][0]=true;
    19             else d[i][0]=false;
    20 
    21         for (int i=1;i<=len1;i++)
    22             for (int j=1;j<=len2;j++)
    23                 if (d[i-1][j] && s1.charAt(i-1)==s3.charAt(i+j-1))
    24                     d[i][j]=true;
    25                 else if (d[i][j-1] && s2.charAt(j-1)==s3.charAt(i+j-1))
    26                     d[i][j]=true;
    27                 else d[i][j]=false;
    28 
    29 
    30         return d[len1][len2];        
    31     }
    32 }
  • 相关阅读:
    CentOS7安装minio
    xshell连接虚拟机Connection failed
    Mysql时间加减函数
    mysql存储过程模板
    Activiti实现会签功能
    2018考研复试流程
    C编程经验总结5(剧终)
    《数据结构总结》
    《关于安卓和IOS开发》
    番外特别篇之 为什么我不建议你直接使用UIImage传值?--从一个诡异的相册九图连读崩溃bug谈起
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4117856.html
Copyright © 2020-2023  润新知