Given a string S representing a sentence and another string word, the task is to find the word from S which has the string word as a prefix. If no such word is present in the string, print -1.
Input: S = “Welcome to Geeksforgeeks”, word=”Gee”
The word “Geeksforgeeks” in the sentence has the prefix “Gee”.
Input: s=”Competitive Programming”, word=”kdflk”
No word in the string has “kdflk” as its prefix.
Approach: Follow the steps below to find which word has the given prefix:
- Extract the words from the sentence using the stringstream and store it in a vector of strings.
- Now, traverse the array and check which word contains the given word as its own prefix.
- If found to be true for any word, then print that word. Otherwise, if no such word is found, print -1.
Below is the implementation of the above approach:
Time Complexity: O(L), where L denotes the length of the string S
Auxiliary Space: O(L)
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.
- Longest Common Prefix using Word by Word Matching
- Frequency of smallest character in first sentence less than that of second sentence
- Find the word with most anagrams in a given sentence
- Find shortest unique prefix for every word in a given list | Set 2 (Using Sorting)
- Java program to count the characters in each word in a given sentence
- Sums of ASCII values of each word in a sentence
- Program for length of the longest word in a sentence
- Print longest palindrome word in a sentence
- Program to replace a word with asterisks in a sentence
- Print each word in a sentence with their corresponding average of ASCII values
- Check if a word is present in a sentence
- Construct an Array of Strings having Longest Common Prefix specified by the given Array
- C program to find and replace a word in a File by another given word
- Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring
- C program to Replace a word in a text by another given word
- Pair of integers having least GCD among all given pairs having GCD exceeding K
- Check a given sentence for a given set of simple grammer rules
- Remove all the palindromic words from the given sentence
- Camel case of a given sentence
- Snake case of a given sentence
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.