Given a string, Find the 1st repeated word in a string.
Examples:
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
We have existing solution for this problem please refer Find the first repeated word in a string link. We can solve this problem quickly in python using Dictionary data structure. Approach is simple,
# Function to Find the first repeated word in a string from collections import Counter def firstRepeat(input): # first split given string separated by space # into words words = input.split(' ') # now convert list of words into dictionary dict = Counter(words) # traverse list of words and check which first word # has frequency > 1 for key in words: if dict[key]>1: print (key) return # Driver program if __name__ == "__main__": input = 'Ravi had been saying that he had been there' firstRepeat(input)
Output:
had
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.