使用字典在Python中查找字符串中的第一个重复单词

先决条件: 词典 数据结构

null

给定一个字符串,找出字符串中第一个重复的单词。 例如:

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

我们有解决这个问题的现有方案,请参考 查找字符串中第一个重复的单词 链接我们可以使用python快速解决这个问题 词典 数据结构。方法很简单,

  1. 首先将给定字符串拆分为空格。
  2. 现在,使用 收藏。迭代器(计数器) 方法字典以单词为关键字,以频率为值。
  3. 现在再次遍历单词列表,检查哪个单词的频率大于1。

# 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 )


输出:

had
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享