两个字符串a,b中的最长公共子串

查找两个字符串a,b中的最长公共子串

http://www.nowcoder.com/questionTerminal/181a1a71c7574266ad07f9739f791506

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String str1 = scanner.nextLine();
            String str2 = scanner.nextLine();
            if (str1.length() > str2.length()) {
                String temp = str1;
                str1 = str2;
                str2 = temp;
            }
            System.out.println(fun(str1, str2));
        }
    }


    public static String fun(String str1, String str2) {
        int maxSubStringLen = 1;
        String maxSubString = str1.substring(0, 1);
        for (int sublen = 1; sublen <= str1.length(); sublen++) {
            // 字串遍历次数
            int count = str1.length() - sublen + 1;
            for (int i = 0; i < count; i++) {
                int startIndex = i;
                int endIndex = i + sublen;
                String subStr = str1.substring(startIndex, endIndex);
                if (str2.contains(subStr)) {
                    if (subStr.length() > maxSubStringLen) {
                        maxSubStringLen = subStr.length();
                        maxSubString = subStr;
                    }
                }
            }
        }
        return maxSubString;
    }

}
全部评论

相关推荐

10-13 17:47
门头沟学院 Java
wulala.god:图一那个善我面过,老板网上找的题库面的
点赞 评论 收藏
分享
shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务