import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* 两个字符串中的公共子串
* @author Green.Gee
* @date 2022/11/16 12:32
* @email green.gee.lu@gmail.com
*/
public class CommonPhraseInTowSpace {
/**
*查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。
* 注:子串的定义:将一个字符串删去前缀和后缀(也可以不删)形成的字符串。请和“子序列”的概念分开!
* 输入描述:
* 输入两个字符串
*
* 输出描述:
* 返回重复出现的字符
* 示例1
* 输入:
* abcdefghijklmnop
* abcsafjklmnopqrstuvw
* 输出:
* jklmnop
*
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String a = in.nextLine();
String b = in.nextLine();
int max = Math.max(a.length(),b.length());
if(a.length() == max){
String item = a;
a = b;
b = item;
}
int i = 0;
int maxP = 0;
List<String> result = new ArrayList<>();
while(i < a.length()){
int j = i;
while(j < a.length()){
String o1 = a.substring(i,j + 1);
if(o1.length() >= maxP && b.contains(o1)){
maxP = o1.length();
result.add(o1);
}
j++;
}
i++;
}
final int finalM = maxP;
result = result.stream()
.filter(item -> item.length() == finalM)
.collect(Collectors.toList());
if(result.size() == 0)
return;
System.out.println(result.get(0));
}
}
}
09-08
771
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交