题解 | #交错的字符串#

交错的字符串

http://www.nowcoder.com/practice/9707297a343442458f638a8032811fe7

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s1 string字符串 
     * @param s2 string字符串 
     * @param s3 string字符串 
     * @return bool布尔型
     */
    public boolean stringJudge(String s1, String s2, String s3) {
        // write code here
        int len1 = s1.length();
        int len2 = s2.length();
        int len3 = s3.length();
        if (len1 + len2 != len3) {
            return false;
        }
        boolean[][] dp = new boolean[len1 + 1][len2 + 1];
        for (int i = len1; i > -1; i--) {
            for (int j = len2; j > -1; j--) {
                if (i == len1 && j == len2) {
                    dp[i][j] = true;
                } else if (i == len1) {
                    dp[i][j] = s2.substring(j).equals(s3.substring(i + j));
                } else if (j == len2) {
                    dp[i][j] = s1.substring(i).equals(s3.substring(i + j));
                } else {
                    char chr1 = s1.charAt(i);
                    char chr2 = s2.charAt(j);
                    char chr3 = s3.charAt(i + j);
                    if (chr1 == chr2) {
                        if (chr1 == chr3) {
                            dp[i][j] = dp[i + 1][j] || dp[i][j + 1];
                        }
                    } else {
                        if (chr1 == chr3) {
                            dp[i][j] = dp[i + 1][j];
                        } else {
                            dp[i][j] = dp[i][j + 1];
                        }
                    }
                }
            }
        }
        return dp[0][0];
    }
}
全部评论

相关推荐

牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务