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

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

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str1 = in.nextLine();
            String str2 = in.nextLine();
            getMaxPublicStr(str1, str2);
        }
    }
    /**
    * 查找两个字符串a,b中的最长公共子串
    * 查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。
    * 双指针: 指向短的字符串, 然后遍历 长字符串.contains()
    */
    public static void getMaxPublicStr(String str1, String str2) {
        if (str1.length() > str2.length()) {
            String temp = str1;
            str1 = str2;
            str2 = temp;
        }
        String result = "";
        int left = 0;
        int right = left + 1;
        while (right <= str1.length()) {
            String substr = str1.substring(left, right);
            if (str2.contains(substr)) {
                //表示包含该子串
                if (substr.length() > result.length()) {
                    result = substr;
                    right ++;
                }
            } else {
                //不包含子串
                left++;
                right++;
            }
        }
        System.out.println(result);
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-15 17:24
点赞 评论 收藏
分享
Twilight_m...:还是不够贴近现实,中关村那块60平房子200万怎么可能拿的下来,交个首付还差不多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务