public class StringTest_1 {
/**
* @param args
*/
public static void main(String[] args) {
String s1 = "asdfitcastghjfghjk";
String s2 = "xcitcastvbnm";
String maxSubString = getMaxSubstring(s2, s1);
System.out.println("maxSubstring:" + maxSubString);
}
/*
* 作业1:获取两个字符串的最大相同子串。 "asdfitcastghjfghjk" "xcitcastvbnm" 思路:
* 1,先明确两个字符串的长短,在长串中判断短串是否存在。 2,存在,已找到,说明短串就是最大的相同的。
* 不存在,就将短串按照长度递减的方式,获取短串中的子串并到长串中判断。 3,一旦存在,便结束查找。
*/
public static String getMaxSubstring(String s1, String s2) {
String max, min;
// 明确哪个是长串哪个是短串。
max = (s1.length() > s2.length()) ? s1 : s2;
min = max.equals(s1) ? s2 : s1;
// 验证max和min
// System.out.println("max="+max);
// System.out.println("min="+min);
for (int i = 0; i < min.length(); i++) {
for (int start = 0, end = min.length() - i; end <= min.length(); start++, end++) {
String temp = min.substring(start, end);
if(max.contains(temp)){
return temp;
}
}
}
return null;
}
}
获取两个字符串的最大相同子串
最新推荐文章于 2022-10-12 12:24:40 发布