zoukankan      html  css  js  c++  java
  • 19.2.27 [LeetCode 97] 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

    题意

    给出s1,s2,s3,判断是否能从s3中抽取出若干个字符以原顺序组成字符串和s1相等,并且s3剩下的部分正好组成了s2

    题解

    自然而然想到的dp,很慢

     1 class Solution {
     2 public:
     3     bool isInterleave(string s1, string s2, string s3) {
     4         int l1=s1.length(),l2=s2.length(),l3=s3.length();
     5         vector<vector<vector<bool>>>dp(l1+1,vector<vector<bool>>(l2+1,vector<bool>(l3+1,false)));
     6         dp[0][0][0]=true;
     7         for(int i=0;i<=l1;i++)
     8             for(int j=0;j<=l2;j++){
     9                 if(i>=1&&dp[i-1][j][i+j-1]&&s1[i-1]==s3[i+j-1])
    10                     dp[i][j][i+j]=true;
    11                 else if(j>=1&&dp[i][j-1][i+j-1]&&s2[j-1]==s3[i+j-1])
    12                     dp[i][j][i+j]=true;
    13             }
    14         return dp[l1][l2][l3];
    15     }
    16 };
    View Code

    好吧,我是傻x

     1 class Solution {
     2 public:
     3     bool isInterleave(string s1, string s2, string s3) {
     4         int l1=s1.length(),l2=s2.length(),l3=s3.length();
     5         if(l1+l2!=l3)return false;
     6         vector<vector<bool>>dp(l1+1,vector<bool>(l3+1,false));
     7         dp[0][0]=true;
     8         for(int i=0;i<=l1;i++)
     9             for(int j=0;j<=l2;j++){
    10                 if(i>=1&&dp[i-1][i+j-1]&&s1[i-1]==s3[i+j-1])
    11                     dp[i][i+j]=true;
    12                 else if(j>=1&&dp[i][i+j-1]&&s2[j-1]==s3[i+j-1])
    13                     dp[i][i+j]=true;
    14             }
    15         return dp[l1][l3];
    16     }
    17 };
    View Code
  • 相关阅读:
    “软件工程”课程评价
    我爱淘二次冲刺阶段4
    我爱淘二次冲刺阶段3
    我爱淘二次冲刺阶段2
    MVC框架具体使用
    初次见面- MVC
    设计模式
    读大型网站技术架构后感
    以《淘宝以《淘宝网》为例,描绘质量属性的六个常见属性场景。
    以《淘宝网》为例,描绘质量属性的六个常见属性场景。
  • 原文地址:https://www.cnblogs.com/yalphait/p/10446456.html
Copyright © 2011-2022 走看看