最长公共子串

公式:


代码:

// SubString
public static void LCS(String s1, String s2) {
    int[][] matrix = new int[s1.length() + 1][s2.length() + 1];

    for (int i = 0; i <= s1.length(); i++)
        matrix[i][0] = 0;
    for (int j = 0; j <= s2.length(); j++)
        matrix[0][j] = 0;

    int max = -1;
    int x = -1;
    int y = -1;
    for (int i = 1; i <= s1.length(); i++) {
        for (int j = 1; j <= s2.length(); j++) {
            if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                matrix[i][j] = matrix[i - 1][j - 1] + 1;
            } else {
                matrix[i][j] = 0;
            }
            if (matrix[i][j] > max) {
                max = matrix[i][j];
                x = i;
                y = j;
            }
        }
    }
    // print max length
    System.out.println(max);
    System.out.println(x);
    System.out.println(y);

    // print substring
    Character[] s = new Character[max];
    int k = max;
    int i = x - 1;
    int j = y - 1;
    while (i >= 0 && j >= 0) {
        if (s1.charAt(i) == s2.charAt(j)) {
            s[--k] = s1.charAt(i);
            i--;
            j--;
        } else
            break;
    }
    for (Character c : s) {
        System.out.print(c);
    }
}

你可能感兴趣的:(面试题)