zoukankan      html  css  js  c++  java
  • 0097. Interleaving String (M)

    Interleaving String (M)

    题目

    Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

    An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that:

    • s = s1 + s2 + ... + sn
    • t = t1 + t2 + ... + tm
    • |n - m| <= 1
    • The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...

    Note: a + b is the concatenation of strings a and b.

    Example 1:

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

    Example 2:

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

    Example 3:

    Input: s1 = "", s2 = "", s3 = ""
    Output: true
    

    Constraints:

    • 0 <= s1.length, s2.length <= 100
    • 0 <= s3.length <= 200
    • s1, s2, and s3 consist of lowercase English letters.

    Follow up: Could you solve it using only O(s2.length) additional memory space?


    题意

    判断字符串s1和s2能否通过间隔插入的方法得到s3。

    思路

    动态规划。dp[i][j]为布尔值,表示s1.substring(0,i)和s2.substring(0,j)能否通过间隔插入组成s3.substring(0, i + j)。

    Follow up可以用滚动数组优化到O(s2.length)。


    代码实现

    Java

    class Solution {
        public boolean isInterleave(String s1, String s2, String s3) {
            if (s3.length() != s1.length() + s2.length()) return false;      
           
            boolean[][] dp = new boolean[s1.length() + 1][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[i][j] = true;
                    } else if (i == 0) {
                        dp[i][j] = dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);
                    } else if (j == 0) {
                        dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i - 1);
                    } else {
                        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[s1.length()][s2.length()];
        }
    }
    
  • 相关阅读:
    初识分布式计算:从MapReduce到Yarn&Fuxi
    日志的艺术(The art of logging)
    关于负载均衡的一切:总结与思考
    打印中文dict list的各种姿势
    不想再被鄙视?那就看进来! 一文搞懂Python2字符编码
    什么是分布式系统,如何学习分布式系统
    再论分布式事务:从理论到实践
    从银行转账失败到分布式事务:总结与思考
    git命令
    IntelliJ idea 中使用Git
  • 原文地址:https://www.cnblogs.com/mapoos/p/14843179.html
Copyright © 2011-2022 走看看