问题
给定两个句子 A
和 B。
(句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)
如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
返回所有不常用单词的列表。您可以按任何顺序返回列表。
示例 1:
输入:A = "this apple is sweet", B = "this apple is sour",输出:["sweet","sour"]
示例 2:
输入:A = "apple apple", B = "banana",输出:["banana"]
提示:
1. 0 <= A.length <= 200
2. 0 <= B.length <= 200
3. A
和 B
都只包含空格和小写字母。
思路及代码
class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
# # 方法一:(计数)用字符串的.count()
# # 拼接A, B字符串,对所有单词频度进行计数,输出频度为1的单词。
# words = A.split(" ") + B.split(" ")
# result = []
# for word in words:
# if words.count(word) == 1:
# result.append(word) # .append()是列表类型的,字符串不能用
# return result
# 方法二:(哈希表)word为key,count为value
words = A.split() + B.split()
map = dict()
result = []
for word in words: # 构建哈希表,单词为键,出现的次数是值。
if word in map.keys(): # 若单词不存在已存在的表中,那么计数为1,若已存在,那么计数值加1。
map[word] += 1
else:
map[word] = 1
for key in map.keys(): # 输出出现次数为1的单词(键)
if map[key] == 1:
result.append(key)
return result
知识点
1. .append()是列表的,字符串不能用。
2. .split()用法(参考:Python3 split()用法)
- 默认以所有空字符进行切片,包括空格,换行,制表符等(如下图的words和WORD)
- 若指定字符进行切片,例如下图WORDS,因为原字符串里面不包含逗号,因此最终结果不会实现切片效果。
3. 疑问:Python里面不区分双引号和单引号?(如下图)
4. 区分字符串中 "+" 和 "split() + " 操作。
- 直接字符串 "+",那么for...in...循环时,是一个字符一个字符遍历的。
- 用 .split() 之后,是按照一个单词一个单词来遍历的。
5. .count() 的用法(参考:Python count()的用法)
功能:用于统计字符串里某个字符出现的次数。