zoukankan      html  css  js  c++  java
  • LeetCode-Interleaving String[dp]

    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.

    标签: Dynamic Programming String

    分析:动态规划;设boolean数组dp[i][j]表示字符串s1[0...i-1]和字符串s2[0...j-1]是否可以匹配到字符串s3[0...i+j-1],

    因此有字符s3[i+j-1]可以由字符s1[i-1]或字符s2[j-1]来匹配,所以:

    如果s1[i-1]==s3[i+j-1],则dp[i][j]=dp[i-1][j];

    如果s2[j-1]==s3[i+j-1],则dp[i][j]=dp[i][j-1];

    所以状态转移方程为:dp[i][j]=(dp[i-1][j]&&s1[i-1]==s3[i+j-1])||(dp[i][j-1]&&s2[j-1]==s3[i+j-1])

    参考代码:

    public class Solution {
        public boolean isInterleave(String s1, String s2, String s3) {
                int len1=s1.length();
                int len2=s2.length();
                int len3=s3.length();
                if(len1+len2!=len3)
                    return false;
                boolean dp[][]=new boolean[len1+1][len2+1];
                dp[0][0]=true;
                for(int j=1;j<=len2;j++){
                    dp[0][j]=dp[0][j-1]&&s2.charAt(j-1)==s3.charAt(j-1);
                }
                for(int i=1;i<=len1;i++){
                    dp[i][0]=dp[i-1][0]&&s1.charAt(i-1)==s3.charAt(i-1);
                }
                for(int i=1;i<=len1;i++){
                    for(int j=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));
                    }
                }
                return dp[len1][len2];
        }
    }
  • 相关阅读:
    jquery判断元素是否可见隐藏
    jQuery的replaceWith()函数用法详解
    前端工作面试问题
    Windows下安装sass和compass失败的解决办法
    马尾图案之canvas的translate、scale、rotate的方法详解
    boost bimap
    boost multi index
    boost regex expression
    boost format
    boost lexical_cast
  • 原文地址:https://www.cnblogs.com/xiaolu266/p/7150560.html
Copyright © 2011-2022 走看看