Given a string, Find the 1st repeated word in a string
Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he
The idea is to tokenize the string and store each word and its count in hashmap. Then traverse the string again and for each word of string, check its count in created hashmap.
First repeated word :: had
Method #2: Using built in python functions:
- As all the words in a sentence are separated by spaces.
- We have to split the sentence by spaces using split().
- We split all the words by spaces and store them in a list.
- Use Counter function to count frequency of words
- Traverse the list and check if any word has frequency greater than 1
- If it is present then print the word and break the loop
Below is the implementation:
This article is contributed by Mandeep Singh. 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.