码迷,mamicode.com
首页 > 其他好文 > 详细

29 交叉字符串

时间:2018-08-05 22:32:42      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:determine   char   continue   @param   form   har   public   solution   code   

public class Solution {
/**
* @param s1: A string
* @param s2: A string
* @param s3: A string
* @return: Determine whether s3 is formed by interleaving of s1 and s2
*/
public boolean isInterleave(String s1, String s2, String s3) {
// write your code here
if(s1 == null || s2 == null || s3 == null || s1.length() + s2.length() != s3.length()){
return false;
}

    int n = s1.length(), m = s2.length(), nm = s3.length();
    boolean[][] dp = new boolean[n + 1][m + 1];
    dp[0][0] = true;
    for(int i = 1; i <= n; i++){
        if(s1.charAt(i-1) == s3.charAt(i - 1)){
            dp[i][0] = dp[i-1][0];
        }
    }
    for(int i = 1; i <= m; i++){
        if(s2.charAt(i-1) == s3.charAt(i-1)){
            dp[0][i] = dp[0][i-1];
        }
    }
    
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            if(s1.charAt(i-1) == s3.charAt(i+j - 1)){
                dp[i][j] = dp[i-1][j];
            }
            if(dp[i][j]){
                continue;
            }
            if(s2.charAt(j-1) == s3.charAt(i+j-1)){
                dp[i][j] = dp[i][j-1];
            }
        }
        
    }
    return dp[n][m];
}

}

29 交叉字符串

标签:determine   char   continue   @param   form   har   public   solution   code   

原文地址:https://www.cnblogs.com/jxkun/p/9427392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!