记一道面试题:/*输入内容为两个字符串,以空格分开,如输入: "abcedf abcsd " 找出最长的公子串 ,结果 abc*/

LZ在面试过程中连续两天碰到这道题,以此记录一下

import java.util.*;
/*输入内容为两个字符串,以空格分开,如输入: "abcedf abcsd "
找出最长的公子串 ,结果 abc*/
public class dd {
    public static void main(String[] args) {


        Scanner scanner=new Scanner(System.in);
        while (scanner.hasNext()){

            String string=scanner.nextLine();
            String[] split = string.split(" ");
            String lcs = getLongStr(split[0], split[1]);
            System.out.println("输出最长公子串为:"+lcs);

        }
    }

    private static String getLongStr(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        int minlen = len1 <= len2 ? len1 : len2;
        int max = 0, index = 0;
        String lessstr = len1 <= len2 ? str1 : str2;
        String longstr = len1 <= len2 ? str2 : str1;
        for(int i = 0; i < minlen; i++){
            for(int j = i + 1;j < minlen + 1; j++){
                String temp = lessstr.substring(i, j);
                if(longstr.contains(temp) && temp.length() > max){
                    max = temp.length();
                    index = i;
                }
            }
        }
        return lessstr.substring(index, max + index);
    }


}

猜你喜欢

转载自www.cnblogs.com/matoo-shi/p/12755718.html