97. Interleaving String

来源:互联网 发布:java程序设计基础答案 编辑:程序博客网 时间:2024/06/05 07:54

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.


,更具s1和s2用的量就知道s3用到了哪一位

class Solution {    public boolean isInterleave(String s1, String s2, String s3) {    char[] cs1=s1.toCharArray(), cs2=s2.toCharArray(), cs3=s3.toCharArray();    if(cs1.length + cs2.length != cs3.length)return false;        boolean[][] dp = new boolean[1+s1.length()][1+s2.length()];        dp[0][0] = true;        for(int i=1; i<=cs2.length; i++)        if(cs2[i-1] == cs3[i-1])dp[0][i] = true;        elsebreak;        for(int i=1; i<=cs1.length; i++)        if(cs1[i-1] == cs3[i-1])dp[i][0] = true;        elsebreak;                for(int i=1; i<=cs1.length; i++) {        for(int j=1; j<=cs2.length; j++) {        if(cs1[i-1] == cs3[i+j-1] && dp[i-1][j])        dp[i][j] = true;        if(cs2[j-1] == cs3[i+j-1] && dp[i][j-1])        dp[i][j] = true;        }        }                return dp[cs1.length][cs2.length];    }}