java中求几个字符串的最大公共子串 使用了比较器Comparator

package com.swift;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Max_Substring_Test {

    public static void main(String[] args) {

        /*
         * 几个字符串的最大公共子字符串
         */

        String str1 = "eriousdfndnfdlk";
        String str2 = "dkgfdkgkdjgdjgjksjgksgjsdkjsdierioe";
        String str3 = "ldskfjdskierundsnfjerioejrejrheruer3j43j4hj3";
        String sub;
        
        List<String> list=new ArrayList<String>();

        for (int i = 0; i < str1.length(); i++) {
            sub = str1.substring(0, i);
            
            if(str2.indexOf(sub)!=-1&&str3.indexOf(sub)!=-1) {
//                System.out.println(sub);
                list.add(sub);
            }
        }
        
        Collections.sort(list, new Comparator<String>() {

            @Override
            public int compare(String arg0, String arg1) {
                int i=arg1.length()-arg0.length();
                return i;
            }
            
        });
        
            System.out.println("The max subString is "+list.get(0));
    }

}

 上面方法中测试的子串都是从第一个字母开始的,所以并不完全,子串还有很多,还有从第二个字母开始,从第三个字母开始,等等的子字符串

所以,还应该再加一层循环,把substring(开始参数,结束参数)中开始和结束参数都设置为变量,开始参数从0开始到最后一个字母下标,结束参数起始位置要根据开始参数而定,否则会出现下标异常

package com.swift;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Max_Substring_Test {

    public static void main(String[] args) {

        /*
         * 几个字符串的最大公共子字符串
         */

        String str1 = "eriousdfndnfdlk";
        String str2 = "dkgfdkgkdjgdjgjksjgksgjsdkjsdierioe";
        String str3 = "ldskfjdskierundsnfjerioejrejrheruer3j43j4hj3";
        String sub;

        List<String> list = new ArrayList<String>();

        for (int i = 0; i < str1.length(); i++) {
            for (int j = i; j < str1.length(); j++) {
                System.out.println(sub = str1.substring(i, j+1));

                if (str2.contains(sub)&& str3.contains(sub)) {
                    System.out.println(sub);
                    list.add(sub);
                }
            }
        }

        Collections.sort(list, new Comparator<String>() {

            @Override
            public int compare(String arg0, String arg1) {
                int i = arg1.length() - arg0.length();
                return i;
            }

        });

        System.out.println("The max subString is " + list.get(0));
    }

}

 

posted @ 2018-01-15 20:51  Advancing-Swift  阅读(451)  评论(0编辑  收藏  举报