Shortest substring of a string containing all given words

01 Apr, 2019
Print the shortest sub-string of a string containing all the given words.
In the first example, two solutions are possible: “world is here. this is a life full of ups” and “ups and downs. life is world”.
Initialize HashMap with all the given words which are required to be searched and assign their values as -1.Maintain a counter.Traverse the entire String word by word and do following for each sentence wordIf the sentence word exists in the list of words you’re looking for, update the last position of that word.Increase the total count if the updated last position was not initialized.If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions
Initialize HashMap with all the given words which are required to be searched and assign their values as -1.
Maintain a counter.
Traverse the entire String word by word and do following for each sentence wordIf the sentence word exists in the list of words you’re looking for, update the last position of that word.Increase the total count if the updated last position was not initialized.If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions
If the sentence word exists in the list of words you’re looking for, update the last position of that word.
Increase the total count if the updated last position was not initialized.
If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions
Below is Java implementation of above steps.
// Java program to find the shortest substring of a// string containing all given words using HashMapimport java.io.*;import java.util.*;import java.util.HashMap;  class Shortest {      public static void findShortest(String sentence,                                     String[] words)    {        // Make an array of words from given sentence        // We remove punctuations before splitting.        String replicate = sentence.replace(".", "");        replicate = replicate.replace(", ", "");        replicate = replicate.replace("!", "");        String sent_words[] = replicate.split(" ");          // hashmap to store given words in a map.        HashMap<String, Integer> map = new HashMap<>();        int length = words.length;        for (int i = 0; i < length; i++)            map.put(words[i], -1);          // Traverse through all sentence words        // and if they match with given words        // then mark their appearances in map.        int len_sub = Integer.MAX_VALUE;        int count = 0;        int local_start = 0, local_end = 0;        for (int i = 0; i < sent_words.length; i++) {            if (map.containsKey(sent_words[i]) == true) {                  // If this is the first occurrence                int index = map.get(sent_words[i]);                if (index == -1)                    count++;                  // Store latest index                map.put(sent_words[i], i);                  // If all words matched                if (count == length) {                      // Find smallest index                    int min = Integer.MAX_VALUE;                    for (Map.Entry<String, Integer> m :                                     map.entrySet()) {                        int val = m.getValue();                        if (val < min)                            min = val;                    }                      // Check if current length is smaller                    // then length so far                    int s = i - min;                    if (s < len_sub) {                        local_start = min;                        local_end = i;                        len_sub=s;                    }                }            }        }          // Printing original substring (with punctuations)        // using resultant local_start and local_end.        String[] original_parts = sentence.split(" ");        for (int i = local_start; i <=local_end; i++)            System.out.print(original_parts[i] + " ");    }      // Driver code    public static void main(String args[])    {        String sentence = "The world is here. this is a" +            " life full of ups and downs. life is world.";        String[] words = { "life", "ups", "is", "world" };        findShortest(sentence, words);    }}
Output :
ups and downs. life is 
This article is contributed by Shifa Khan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shubh_123ab
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Real-time application of Data Structures
Find k numbers with most occurrences in the given array
set vs unordered_set in C++ STL
Find the length of largest subarray with 0 sum
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++