编码需求
找出指定的2个字符串的最长公共子串,如果存在多个等长的公共子串,则请按字母序排序,依次打印出所有公共子串,每行一个
编码实现
import java.util.*;
public class Main {
public static List<String> getCommonStr(String str1, String str2) {
boolean oneMoreLength = str1.length() > str2.length();
String maxStr = oneMoreLength ? str1 : str2;
String minStr = oneMoreLength ? str2 : str1;
List<String> list = new ArrayList();
for (int i = 0; i < minStr.length(); i++) {
for (int startIndex = 0, endIndex = minStr.length() - i; endIndex <= minStr.length(); startIndex++,endIndex++) {
String temp=minStr.substring(startIndex, endIndex); //截取的那个。
if(maxStr.contains(temp)){
list.add(temp);
}
}
if (list.size() > 0) {
return list;
}
}
return list;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str1 = scanner.next();
String str2 = scanner.next();
List<String> result = getCommonStr(str1, str2);
result.stream().sorted((a,b) -> {return a.compareTo(b);}).forEach(str -> System.out.println(str));
}
}