例如找到字符串"abcwerthelloyuiodef"和"cvhellobnm"中的最大相同字串 此题,应该从子串的长度考虑。)
题目描述
获取两个字符串中最大相同子串
例如找到字符串"abcwerthelloyuiodef"和"cvhellobnm"中的最大相同字串 此题,应该从子串的长度考虑。
思路:
1,将短的那个子串按照长度递减的方式获取到。
2,将每获取到的子串去长串中判断是否包含,如果包含,已经找到!。
代码
import java.util.Arrays;
public class Test {
String maxstring(String str1,String str2){
//外层循环确定子串长度的种类数量,且此函数默认str2长度小
for(int i=0;i<str2.length();i++){
//内层循环用来确定同一长度字串共有几种
for(int j=0,k=str2.length()-i;k<=str2.length();j++,k++){
String temp=str2.substring(j,k);
if(str1.contains(temp)){
return temp;
}
}
}
return null;
}
public static void main(String[] args){
Test t=new Test();
System.out.println(t.maxstring("abcwerthelloyuiodef","cvhellobnm"));
}
}
结果
hello