1. 程式人生 > 其它 >Leetcode 97 交錯字串 二維DP

Leetcode 97 交錯字串 二維DP

 

  C:

bool search(char *s1, char *s2, char *s3, int p1, int p2, int *cache)
{
    int len1 = strlen(s1), len2 = strlen(s2), len3 = strlen(s3);
    if (p1 == len1 && p2 == len2)
        return true;
    if (cache[p1 * (len2 + 1) + p2] == -1)
        return false;
    int p3 = p1 + p2;
    char
c1 = NULL, c2 = NULL; if (p1 < len1) c1 = s1[p1]; if (p2 < len2) c2 = s2[p2]; char c3 = s3[p3]; if (c1 != NULL && c1 == c3 && search(s1, s2, s3, p1 + 1, p2, cache)) return true; if (c2 != NULL && c2 == c3 && search(s1, s2, s3, p1, p2 + 1
, cache)) return true; cache[p1 * (len2 + 1) + p2] = -1; return false; } bool isInterleave(char *s1, char *s2, char *s3) { int len1 = strlen(s1), len2 = strlen(s2), len3 = strlen(s3); if (len1 + len2 != len3) return false; int *cache = malloc(sizeof(int) * (len1 + 1
) * (len2 + 1)); memset(cache, 0, sizeof(int) * (len1 + 1) * (len2 + 1));
    bool re = search(s1, s2, s3, 0, 0, cache);     free(cache);     return re;
}

  JAVA:

    public final boolean isInterleave(String s1, String s2, String s3) {
        int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
        if (len1 + len2 != len3) return false;
        int[][] cache = new int[len1 + 1][len2 + 1];
        return search(s1, s2, s3, 0, 0, cache);
    }

    private final boolean search(String s1, String s2, String s3, int point1, int point2, int[][] cache) {
        if (point1 == s1.length() && point2 == s2.length()) return true;
        if (cache[point1][point2] == -1) return false;
        char c1 = '0', c2 = '0';
        if (point1 < s1.length()) c1 = s1.charAt(point1);
        if (point2 < s2.length()) c2 = s2.charAt(point2);
        char c3 = s3.charAt(point1 + point2);
        if (c1 != '0' && c1 == c3 && search(s1, s2, s3, point1 + 1, point2, cache)) return true;
        if (c2 != '0' && c2 == c3 && search(s1, s2, s3, point1, point2 + 1, cache)) return true;
        cache[point1][point2] = -1;
        return false;
    }

  JS:

/**
 * @param {string} s1
 * @param {string} s2
 * @param {string} s3
 * @return {boolean}
 */
var isInterleave = function (s1, s2, s3) {
    let len1 = s1.length, len2 = s2.length, len3 = s3.length;
    if (len1 + len2 != len3) return false;
    let cache = new Array(len1 + 1);
    for (let i = 0; i <= len1; i++) cache[i] = new Array(len2 + 1);
    return search(s1, s2, s3, 0, 0, 0, cache);
};

var search = function (s1, s2, s3, p1, p2, cache) {
    if (p1 == s1.length && p2 == s2.length) return true;
    if (cache[p1][p2] == -1) return false;
    let c1, c2;
    if (p1 < s1.length) c1 = s1.charAt(p1);
    if (p2 < s2.length) c2 = s2.charAt(p2);
    let c3 = s3.charAt(p1 + p2);
    if (c1 && c1 == c3 && search(s1, s2, s3, p1 + 1, p2, cache)) return true;
    if (c2 && c2 == c3 && search(s1, s2, s3, p1, p2 + 1, cache)) return true;
    cache[p1][p2] = -1;
    return false;
}