简体   繁体   中英

How to check if 2 strings have common substrings with n letters

I ask to write code that checks if 2 strings have common substrings with n letters. The n variable will be input by the user and that is how many letters it needs to find in common.

For instance, if I input n=2 and these are the two strings:

"THE FIRST BANK OF AMERICA"
"A MAN NAMED ICARUS WANTED TO FLY TO THE SUN "

it will print this:

TH HE E F AN AM ME IC CA 

I need the code to be simple because we just started, so I can't use any special library from Java.

I'd go over each string, extract the n-lengthed substrings to a set, and then intersect the two:

public static void main(String[] args) {
    int n = 2;
    String s1 = "THE FIRST BANK OF AMERICA";
    String s2 = "A MAN NAMED ICARUS WANTED TO FLY TO THE SUN";

    Set<String> substrings1 = getSubstrings(s1, n);
    Set<String> substrings2 = getSubstrings(s2, n);

    substrings1.retainAll(substrings2);
    System.out.println(substrings1);
}

private static Set<String> getSubstrings(String s, int n) {
    return IntStream.range(0, s.length() - n + 1)
                    .mapToObj(i -> s.substring(i, i + n))
                    .collect(Collectors.toCollection(LinkedHashSet::new));
}

Note: \

  1. I've used a Collectors.toCollection(LinkedHashSet::new) to preserve the order of the substrings to get the output in the same order as specified in the question. If the order is immaterial, you could use Collectors.toSet() instead which would be a tad faster.
  2. This sample uses a hard-coded n and two strings. The same algorithm can of course be applied to user input, but I'm leaving that out for brevity's sake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM