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 word
- 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.
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 firstname.lastname@example.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Shortest Palindromic Substring
- Check if the given string of words can be formed from words present in the dictionary
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
- Check if given string is a substring of string formed by repeated concatenation of z to a
- Find length of longest subsequence of one string which is substring of another string
- Queries to check if string B exists as substring in string A
- Minimum changes required to make first string substring of second string
- Check if the given string is shuffled substring of another string
- Lexicographically all Shortest Palindromic Substrings from a given string
- Reverse words in a given string
- Count words in a given string
- Check if given words are present in a string
- Reverse words in a given String in Java
- Minimum Distance Between Words of a String
- Reverse middle words of a string
- Count words present in a string
- Program to extract words from a given String
- Program to reverse words in a given string in C++
- Print all funny words in a string
Improved By : shubh_123ab