写了一下,不知道有没有简便方法
package com.itheima.check;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个字符串:");
String s1 = sc.nextLine();
System.out.println("请输入第二个字符串:");
String s2 = sc.nextLine();
getMaxSubstring(s1,s2);
}
public static void getMaxSubstring(String s1,String s2) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < s1.length(); i++) {
for (int j = i + 1; j <= s1.length(); j++) {
if (s2.indexOf(s1.substring(i,j)) != -1) {
list.add(s1.substring(i,j));
}
}
}
TreeSet<String> set = new TreeSet<String>();
if(list.size() == 0) {
System.out.println(s1 + "和" + s2 + "没有相同的子字符串");
return;
}else {
String max = list.get(0);
for (String s : list) {
if (s.length() > max.length()) {
max = s;
}
}
set.add(max);
for (String s : list) {
if (s.length() == max.length()) {
set.add(s);
}
}
}
System.out.println(s1 + "和" + s2 + "的最大相同子字符串如下:");
for (String s : set) {
System.out.print(s + " ");
}
}
} |