題目描述
查找兩個字符串a,b中的最長公共子串
輸入描述
輸入兩個字符串
輸出描述
返回重複出現的字符
輸入例子
abcdefghijklmnop
abcsafjklmnopqrstuvw
輸出例子
jklmnop
算法實現
import java.util.Scanner;
/**
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
String a = scanner.nextLine();
String b = scanner.nextLine();
System.out.println(findMaxSubstring(a, b));
}
scanner.close();
}
/**
* Substring問題不光要求下標序列是遞增的,還要求每次
* 遞增的增量爲1, 即兩個下標序列爲:
* < i, i+1, i+2, ..., i+k-1 > 和 < j, j+1, j+2, ..., j+k-1 >
* 類比Subquence問題的動態規劃解法,Substring也能夠用動態規劃解決,令
* c[i][j]表示【包含Xi字符】和【Yi字符】的最大Substring的長度,好比
* X = < y, e, d, f >
* Y = < y, e, k, f >
* c[1][1] = 1
* c[2][2] = 2
* c[3][3] = 0
* c[4][4] = 1
* 動態轉移方程爲:
* 若是xi == yj, 則 c[i][j] = c[i-1][j-1]+1
* 若是xi != yj, 那麼c[i][j] = 0
* 最後求Longest Common Substring的長度等於
* max{c[i][j], 1 <= i <= n, 1 <= j<= m}
*
* @param a
* @param b
* @return
*/
private static String findMaxSubstring(String a, String b) {
// 下面的if只是爲了經過測試,沒有必要
if (a.length() > b.length()) {
String s = a;
a = b;
b = s;
}
int aLen = a.length() + 1;
int bLen = b.length() + 1;
int max = 0;
int x = 0;
int[][] c = new int[aLen][bLen];
for (int i = 0; i < aLen; i++) {
c[i][0] = 0;
}
for (int i = 0; i < bLen; i++) {
c[0][i] = 0;
}
for (int i = 1; i < aLen; i++) {
for (int j = 1; j < bLen; j++) {
if (a.charAt(i - 1) == b.charAt(j - 1)) {
c[i][j] = c[i - 1][j - 1] + 1;
} else {
c[i][j] = 0;
}
if (c[i][j] > max) {
max = c[i][j];
x = i;
}
}
}
return a.substring(x - max, x);
}
}