zoukankan      html  css  js  c++  java
  • 97. Interleaving String

    题目:

    Given s1s2s3, 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.

    链接:  http://leetcode.com/problems/interleaving-string/

    题解:

    依然是使用dynamic programming。和Edit Distance很像。假设我们构建一个棋盘,s1代表行,s2代表列,每次只能向右或者向下走,最后看s3这条路径能不能够从左上到达右下。

    Time Complexity - O(m * n), Space Complexity - O(m * n)。

    public class Solution {
        public boolean isInterleave(String s1, String s2, String s3) {
            if(s1 == null || s2 == null || s3 == null)
                return true;
            int m = s1.length(), n = s2.length(), s = s3.length();
            if(m + n != s)
                return false;
            boolean[][] dp = new boolean[m +1][n + 1];
            dp[0][0] = true;
            
            for(int i = 0; i < m + 1; i++) {
                for(int j = 0; j < n + 1; j++) {
                    if(dp[i][j] == true
                    || (j - 1 >= 0 && dp[i][j - 1] == true && s2.charAt(j - 1) == s3.charAt(i + j - 1))
                    || (i - 1 >= 0 && dp[i - 1][j] == true && s1.charAt(i - 1) == s3.charAt(i + j - 1))) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = false;
                    }
                }
            }
            
            return dp[m][n];
        }
    }

    还看到有大神用BFS来做,原理其实和DP差不多,复杂度也基本一样,列在参考里了。

    题外话:  从9月12号开始,到今天为止,基本leetcode的第一遍就做了100题了,有两道没做,Text Justification和Wild Card Matching, 打算学一学Automata以后再来挑战这几道。同时还想学习一下Mining Massive Datasets以及基本的Python编程。 目标很多,时间很少,希望一切顺利吧。(10-12-2015)。

    Reference:

    http://www.cnblogs.com/springfor/p/3896159.html

    https://leetcode.com/discuss/19973/8ms-c-solution-using-bfs-with-explanation                  <- BFS

    https://leetcode.com/discuss/22726/dp-solution-in-java

    https://leetcode.com/discuss/4667/is-there-a-better-algorithm-than-what-i-give

    https://leetcode.com/discuss/11694/my-dp-solution-in-c

    https://leetcode.com/discuss/16086/my-solution-in-java-using-dp-time-o-n-m-and-space-o-m

  • 相关阅读:
    HDU1029 Ignatius and the Princess IV
    UVA11039 Building designing【排序】
    UVA11039 Building designing【排序】
    POJ3278 HDU2717 Catch That Cow
    POJ3278 HDU2717 Catch That Cow
    POJ1338 Ugly Numbers(解法二)
    POJ1338 Ugly Numbers(解法二)
    UVA532 Dungeon Master
    UVA532 Dungeon Master
    POJ1915 Knight Moves
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4437171.html
Copyright © 2011-2022 走看看