判断字符串s中是否有重复单词,并输出这些重复单词
时间: 2023-11-28 21:48:06 浏览: 29
可以先将字符串s按照空格分割成单词列表,然后使用一个集合来存储已经遍历过的单词,如果当前单词已经在集合中出现过,就将其添加到结果列表中。最后返回结果列表即可。
以下是Python代码实现:
```python
def find_duplicate_words(s):
words = s.split()
visited = set()
duplicates = []
for word in words:
if word in visited and word not in duplicates:
duplicates.append(word)
visited.add(word)
return duplicates
```
示例:
```python
s = "hello world hello world"
print(find_duplicate_words(s)) # ['hello', 'world']
```
注意,上述实现只能找出完全相同的重复单词,如果两个单词只是大小写不同,它们会被视为不同的单词。如果需要忽略大小写,可以将所有单词转换为小写或大写形式再进行比较。
相关问题
判断字符串s中是否有重复单词并输出这些重复单词
可以使用哈希表来解决这个问题。
具体步骤如下:
1. 将字符串s按照空格分割成单词数组words。
2. 遍历单词数组words,使用哈希表来统计每个单词出现的次数。
3. 如果某个单词出现的次数大于1,则说明出现了重复单词,将其输出。
以下是Python代码实现:
```python
def find_duplicate_words(s):
words = s.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
duplicates = [word for word, count in word_count.items() if count > 1]
if duplicates:
print("重复单词:", ", ".join(duplicates))
else:
print("没有重复单词。")
```
示例输入和输出:
```python
find_duplicate_words("hello world hello")
# 输出:重复单词:hello
find_duplicate_words("the quick brown fox jumps over the lazy dog")
# 输出:没有重复单词。
```
defq3(s:str)判断字符串s中是否有重复单词并输出这些重复单词
可以使用 Python 中的 Counter 类来实现这个功能。首先,将字符串 s 按照空格划分为单词列表,然后使用 Counter 统计每个单词出现的次数,最后输出出现次数大于 1 的单词即可。
以下是代码示例:
```python
from collections import Counter
def defq3(s: str):
words = s.split()
counter = Counter(words)
duplicates = [word for word, count in counter.items() if count > 1]
if duplicates:
print("重复单词为:", ', '.join(duplicates))
else:
print("字符串中没有重复单词。")
```
例如,调用 `defq3('this is a test string with some words and some repeated words')`,输出结果为:
```
重复单词为: is, some, words, and
```