LeetCode 55 Interleaving String

来源:互联网 发布:淘宝内存卡骗局大全 编辑:程序博客网 时间:2024/05/23 02:04

Given s1, s2, s3, 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.

分析:

小妹妹说的没错,看见一个问题像贪心的时候,就该想想动规先,面试时不会出贪心这么直观的问题给你分析的。

设 mat[i][j] 表示s1从头开始长度为i子串和s2从头开始长度为j子串是否交叉成s3上从头开始长度(i+j)长度子串的结果,我们可以看出,这个问题跟最终问题是同质的,只是规模不同,这符合动态规划的标准。

接下来找状态转移方程:

mat[i][j] = mat[i-1][j] && (s1.charAt(i-1) == s3.charAt(i+j-1)) 

或者

mat[i][j] = mat[i][j-1] && (s2.chatAt(j-1) == s3.charAt(i+j-1))

接下来考虑初始化,

mat[0][0] 应该是true, 否则后面&&关系永远是false,另外初始化mat[i][0],mat[0][j].

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


0 0