LeetCode - Interleaving String

https://leetcode.com/problems/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.

這道題用DP做很簡單, match[i][j]表示s3的前i+j個字符是由s1的前i個和s2的前j個字符組成的。

那麼轉換公式就是:

if(s1.charAt(i-1) == s3.charAt(i+j-1) && match[i-1][j]) match[i][j] = true;

if(s2.charAt(j-1) == s3.charAt(i+j-1) && match[i][j-1]) match[i][j] = true;

其餘情況就爲false

代碼如下:

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

如果s1的長度爲m,s2長度爲n,時間複雜度和空間複雜度都是O(m*n)


發佈了129 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章