- /*需求:获取两个字符串的最大子字符串
- *思路:1、比较两个字符串,选出较短的字符串
- * 2、若长字符串包含短字符串,则返回;否则将短字符串截取长度-1的子串
- * 3、反复判断长字符串是否包含子串,包含则找到,否则继续截取
- */
- public class MaxSameString {
- public static void main(String[] args) {
- String s1 = "abcdefg anothersame same";
- String s2 = "ab anothersame d same";
- System.out.println(s1);
- System.out.println(s2);
- System.out.println("maxSameString = " + maxSameString(s1, s2));
- }
-
- static String maxSameString(String string, String otherString){
- String longStr, shortStr;
-
- //选出长字符串和短字符串
- longStr = string.length() > otherString.length() ? string : otherString;
- shortStr = longStr == string ? otherString : string;
-
- //记录子串结尾后一位索引
- int end = shortStr.length();
- //记录临时最大子串
- String maxString = "";
- //记录临时最大子串的长度
- int length = 0;
-
- while(end > 0){
- //end - i > length的作用:end - i表示截取的temp字符串长度
- //如果temp长度不大于临时最大子串的长度,那不必比较longStr.contains(temp)
- for (int i = 0; i < end && end - i > length; i++) {
- String temp = shortStr.substring(i, end);
- if(longStr.contains(temp)){
- //更新最长子串记录
- maxString = temp;
- length = temp.length();
- }
- }
-
- //将子串最后一位截掉
- --end;
- shortStr = shortStr.substring(0, end);
- }
- return maxString;
- }
- }
复制代码
|
|