zoukankan      html  css  js  c++  java
  • 【Lintcode】029.Interleaving String

    题目:

    Given three strings: s1s2s3, determine whether s3 is formed by the interleaving of s1 and s2.

    Example

    For s1 = "aabcc", s2 = "dbbca"

    • When s3 = "aadbbcbcac", return true.
    • When s3 = "aadbbbaccc", return false.

    题解:

    Solution 1 ()

    class Solution {
    public:
        bool isInterleave(string s1, string s2, string s3) {
            int n1 = s1.size(), n2 = s2.size(), n3 = s3.size();
            if (n1 + n2 != n3) {
                return false;
            }
            vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, false));
            dp[0][0] = true;
            for (int i = 1; i <= n1; ++i) {
                dp[i][0] = dp[i - 1][0] && (s1[i - 1] == s3[i - 1]);
            }
            for (int i = 1; i <= n2; ++i) {
                dp[0][i] = dp[0][i - 1] && (s2[i - 1] == s3[i - 1]);
            }
            for (int i = 1; i <= n1; ++i) {
                for (int j = 1; j <= n2; ++j) {
                    dp[i][j] = (dp[i - 1][j] && s1[i - 1] == s3[i - 1 + j]) || (dp[i][j - 1] && s2[j - 1] == s3[j - 1 + i]);
                }
            }
            return dp[n1][n2];
        }
    };

    Solution  2 ()

    class Solution {
    public:
        bool isInterleave(string s1, string s2, string s3) {
            if(s1.length() + s2.length() != s3.length())
            return false;
            bool dp[s2.length() + 1];
            for(int i = 0; i <= s1.length(); i++){
                for(int j = 0; j <= s2.length(); j++){
                    if(i == 0 && j == 0)
                    dp[j] = true;
                    else if(i == 0)
                    dp[j] = (dp[j - 1] && s3[i + j - 1] == s2[j - 1]);
                    else if(j == 0)
                    dp[j] = (dp[j] && s3[i + j - 1] == s1[i - 1]);
                    else
                    dp[j] = (dp[j] && s3[i + j - 1] == s1[i - 1]) || (dp[j - 1] && s3[i + j - 1] == s2[j - 1]);
                }
            }
            return dp[s2.length()];
        }
    };

      DFS

    Solution 3 ()

      BFS

    Solution 4 ()

  • 相关阅读:
    二、JVM — 垃圾回收
    一、JVM — Java内存区域
    四、JVM — 类文件结构
    java 如何重写equal 和hashcode方法(最佳实践)
    Java关于继承中的内存分配
    Linux — 基础知识
    Zookeeper — 应用场景
    分布式服务接口请求的顺序性如何保证?
    如何设计一个高并发系统?
    索引策略
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6884025.html
Copyright © 2011-2022 走看看