public static String maxString(String one, String two) {
if (one == null || two == null) {
return null;
}
if (one.equals("") || two.equals("")) {
return null;
}
// 二者中较长的字符串
String max = "";
// 二者中较短的字符串
String min = "";
if (one.length() < two.length()) {
max = two;
min = one;
} else {
max = one;
min = two;
}
String current = "";
// 遍历较短的字符串,并依次减少短字符串的字符数量,判断长字符是否包含该子串
for (int i = 0; i < min.length(); i++) {
for (int begin = 0, end = min.length() - i; end <= min.length(); begin++, end++) {
current = min.substring(begin, end);
if (max.contains(current)) {
return current;
}
}
}
return null;
}
@Test
public void test() {
String strOne = "abcdefg";
String strTwo = "adefgwgeweg";
String result = maxString(one, two);
System.out.println(result);
给2个字符串,求两个字符串的最长子串
最新推荐文章于 2023-03-22 23:29:14 发布