Java - Write code to generate Sub Words

Requirements

Write code to generate Sub Words

Demo

//package com.book2s;
import java.util.LinkedHashSet;

import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        String word = "book2s.com";
        int length = 2;
        System.out.println(generateSubWords(word, length));
    }//from  w w w  .  j a v a  2  s.c  o  m

    public static Set<String> generateSubWords(String word, int length) {
        if (length > word.length())
            throw new IllegalArgumentException("The word '" + word
                    + "' length cannot be less than the length " + length
                    + " of the words to be generated.");

        // LinkedHashSet maintains the order. if there are multiple common substrings the left most should match first.
        Set<String> generatedWords = new LinkedHashSet<>();
        for (int i = 0; i <= (word.length() - length); i++)
            generatedWords.add(word.substring(i, length + i));

        return generatedWords;
    }
}

Related Exercise