交错字符串有三个或四个字符串

时间:2017-04-04 16:46:19

标签: string algorithm dynamic-programming

我使用动态编程(使用2D矩阵)实现了2个字符串的交错字符串问题,现在我想对3个或4个字符串执行相同操作。我无法弄清楚如何操纵索引。有人可以用3D或4D矩阵帮助我吗?

例如:s1 = 1,s2 = simple,s3 = example,res = onsimexepleample - > TRUE

UPDATE ** 交错字符串问题:给定三个字符串A,B和C.如果C包含A和B的所有字符以及所有字符的顺序,则称其为交错A和B.在单个字符串中保留。

两个字符串

实施

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

}

1 个答案:

答案 0 :(得分:1)

好的以下是我对三维字符串记忆的Java实现:

public class Solution {
    public boolean isInterleaving(int i, int j, int k, String s1, String s2, String s3, String S,
            boolean dp[][][], boolean visited[][][]) {

        if (i == s1.length() && j == s2.length() && k == s3.length()) {
            return true;
        }

        if(visited[i][j][k]) {
            return dp[i][j][k];
        }

        visited[i][j][k] = true;
        if (i < s1.length() && s1.charAt(i) == S.charAt(i + j + k)) {
            if (isInterleaving(i + 1, j, k, s1, s2, s3, S, dp, visited)) {
                return dp[i][j][k] = true;
            }
        }

        if (j < s2.length() && s2.charAt(j) == S.charAt(i + j + k)) {
            if (isInterleaving(i, j + 1, k, s1, s2, s3, S, dp, visited)) {
                return dp[i][j][k] = true;
            }
        }

        if (k < s3.length() && s3.charAt(k) == S.charAt(i + j + k)) {
            if (isInterleaving(i, j, k + 1, s1, s2, s3, S, dp, visited)) {
                return dp[i][j][k] = true;
            }
        }

        return dp[i][j][k] = false;
    }

    public boolean isInterleave(String s1, String s2, String s3, String S) {
        if (S.length() != s1.length() + s2.length() + s3.length()) {
            return false;
        }
        boolean dp[][][] = new boolean[s1.length() + 1][s2.length() + 1][s3.length() + 1];
        boolean visited[][][] = new boolean[s1.length() + 1][s2.length() + 1][s3.length() + 1];

        return isInterleaving(0, 0, 0, s1, s2, s3, S, dp, visited);
    }
}

希望它有所帮助!如果你不理解任何部分,我会做一些解释:)