求两个字符串的最长公共子串

    public static String findLongestOfTheSame(String s1,String s2) {

        char[] c1=s1.toCharArray();

        char[] c2=s2.toCharArray();

        int l1=c1.length;

        int l2=c2.length;

        int count=0,maxLength=0,start=0,end=0;

        boolean hasTheSame=false;

        for(int i=0;i<l1;i++)

        {

            count=0;

            for(int j=0;j<l2;j++)

            {

                if(c1[i]==c2[j])

                {

                    hasTheSame=true;

                    do

                    {

                        count++;

                        if(count>maxLength)

                        {

                            maxLength=count;

                            start=i;

                            end=i+count;

                        }

                    }while(i+count<l1 && j+count<l2 && c1[i+count]==c2[j+count]);

                    count=0;

                }

            }

        }

        return new String(hasTheSame?Arrays.copyOfRange(c1, start, end):null);

    }

 

你可能感兴趣的:(字符串)