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

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

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

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str1 = scan.nextLine();
        String str2 = scan.nextLine();
        String largest = str1.length() >= str2.length() ? str1 : str2;
        String smallest = str1.length() < str2.length() ? str1 : str2;
        char[] chrs1 = smallest.toCharArray();
        char[] chrs2 = largest.toCharArray();
        int ml = 0;
        String ans = "";
        for (int i = 0; i < chrs1.length; i++) {
            for (int j = 0; j < chrs2.length; j++) {
                if (chrs1[i] == chrs2[j]) {
                    int p = 0;
                    while (i + p < chrs1.length && j + p < chrs2.length && chrs1[i + p] == chrs2[j + p]) {
                        p++;
                    }
                    if (p > ml) {
                        ans = largest.substring(j, j + p);
                        ml = ans.length();
                    }
                }
            }
        }
        System.out.println(ans);
    }
}
全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞
送花
回复
分享
发布于 2022-04-20 16:59

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务