import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
/**
* @ClassName: Que
* @Description: 获取两个字符串的最长相同子串,例如abegad与acegab,最大相同子串为ega。
* @Author: Wanglt
* @CreateDate: 2020年2月29日
*
*/
public class Que {
private String str1;
private String str2;
private int[][] temp;
public Que1(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
this.temp = new int[str1.length() + 1][str2.length() + 1];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串A");
String str1 = scanner.next();
System.out.println("请输入字符串B");
String str2 = scanner.next();
// String str1 = "abceba";
// String str2 = "bcba";
Que1 que1 = new Que1(str1, str2);
System.out.println("最大相同子串:" + que1.LongestSub());
}
public String LongestSub() {
String res = "";
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
temp[i + 1][j + 1] = temp[i][j] + 1;
}
}
}
if (findMax() != null) {
for (String s : findMax()) {
res = res + s + " ";
}
} else {
res = "不存在";
}
printTemp();
return res;
}
/**
* 找最大子串
*/
public List<String> findMax() {
LinkedList<String> list = new LinkedList();
int[] point = new int[str1.length()];
String res = "";
int max = 0;
int x = 0;
int y = 0;
for (int i = 1; i < temp.length; i++) {
for (int j = 1; j < temp[0].length; j++) {
if (temp[i][j] > max) {
max = temp[i][j];
point = new int[str1.length()];
point[i - 1] = j - 1;
} else if (max != 0 && temp[i][j] == max) {
point[i - 1] = j - 1;
}
}
}
if (max == 0) {
return null;
}
for (int i = 0; i < point.length; i++) {
if (point[i] != 0) {
x = i;
y = point[i];
while (temp[x + 1][y + 1] != 0) {
res = str1.charAt(x) + res;
x--;
y--;
}
list.add(res);
res = "";
}
}
return list;
}
/**
* 输出temp[][]
*/
public void printTemp() {
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < temp[0].length; j++) {
System.out.print(temp[i][j] + " ");
}
System.out.println();
}
}
}
运行截图: