- 总体思路:看短的字符串以及他的所有子串是否包含在长的字符串中
- 详细步骤:
- 将短的字符串str1截取出来,截取的长度从短字符串长度str1.length()开始不断缩小
- 所有截取出的子串都在长的字符串str2中查找是否可以匹配
- 第一个匹配成功的子串就是两个字符串的公共最大相同子串,若匹配不成功,则证明没有相同子串。
- 将截取的子串长度作为外层循环(初始长度为str1的长度,每次循环长度-1)
- 将截取子串的起始位置作为内层循环(从下标为0开始,每次循环起始下标+1)
以下两个字符串为例:
String str1 = "memo please hello while java be a boy";
String str2 = "hello my friend girl java helle while java can you be a bird";
最大相同子串应该是“ while java ”
- 详细代码
public class StringTask4 {
public static void main(String[] args) {
//准备字符串
String str1 = "memo please hello while java be a boy";
String str2 = "hello my friend girl java helle while java can you be a bird";
//嵌套循环匹配
for (int i = str1.length(); i > 0 ; i--) {//长度更短的字符串长度作为外层循环,i为子串长度。
for (int j = 0; j < str1.length() - i; j++) {//每次需要比较的子串个数是(字符串长度 - 子串长度),j是截取子串的起始位置
String str = str1.substring(j,j + i);//按照长度和起始下标取出子串
if (str2.indexOf(str) != -1){//判断另一个字符串里有没有这个子串,有的话直接返回子串(最大相同子串),没有继续循环
System.out.println("最大相同子串是:" + str);
return;
}
}
}
//进行到这里说明任何长度的子串都没有匹配成功,没有相同子串
System.out.println("没有相同子串");
}
}
- 运行结果