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

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

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

import java.util.*;
import java.util.stream.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\n");
        while (scanner.hasNext()) {
            String S = scanner.next();
            String T = scanner.next();
            if (S.equals(T)) {
                System.out.println(S);
                continue;
            } else if (S.contains(T)) {
                System.out.println(T);
                continue;
            } else if (T.contains(S)) {
                System.out.println(S);
                continue;
            }
            //List<String> list = new ArrayList<>();
            HashMap<Integer, String> hashMap = new HashMap<>();
            String shortS = S.length()>=T.length()?T:S;
            String longS = S.length()<T.length()?T:S;
            int max = shortS.length();
            while (max-->0) {
                int left = 0;
                int right = max-left-1;
                //if (!list.isEmpty()) break;
                if (!hashMap.isEmpty()) break;
                while (right<longS.length()) {
                    if (shortS.contains(longS.substring(left, right+1))) {
                        //list.add(longS.substring(left, right+1));
                        hashMap.put(shortS.indexOf(longS.substring(left, right+1)), longS.substring(left, right+1));
                    }
                    left++;
                    right++;
                }
            }
            Optional<Map.Entry<Integer, String>> min = hashMap.entrySet().stream().min(Map.Entry.comparingByKey());
            System.out.println(min.get().getValue());
        }
    }
}

全部评论
请大家指教
点赞 回复 分享
发布于 2023-01-22 11:06 河南

相关推荐

Noob1024:一笔传三代,人走笔还在
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务