English:
We are given two sentences
A
andB
. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list in any order.
Example 1:
Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]
Example 2:
Input: A = "apple apple", B = "banana"
Output: ["banana"]
Note:
0 <= A.length <= 200
0 <= B.length <= 200
A
andB
both contain only spaces and lowercase letters.
中文:
给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)
如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
返回所有不常用单词的列表。
您可以按任何顺序返回列表。
示例 1:
输入:A = "this apple is sweet", B = "this apple is sour"
输出:["sweet","sour"]
示例 2:
输入:A = "apple apple", B = "banana"
输出:["banana"]
提示:
0 <= A.length <= 200
0 <= B.length <= 200
A 和 B 都只包含空格和小写字母。
1.
开始我是将两句分开来处理。明显显得很拥挤,代码有点啰嗦。
class Solution(object):
def uncommonFromSentences(self, A, B):
"""
:type A: str
:type B: str
:rtype: List[str]
"""
word_a = A.split(' ')
d_a = {k:0 for k in word_a}
word_b = B.split(' ')
d_b = {k:0 for k in word_b}
for x in word_a:
d_a[x] += 1
for y in word_b:
d_b[y] += 1
for k in d_a.keys():
if d_a[k]==1:
if k not in result and k not in d_b:
result.append(k)
for k in d_b.keys():
if d_b[k]==1:
if k not in result and k not in d_a:
result.append(k)
return result
理解还是很好理解的,后面我就把两个句子放到一起去处理了。
2.
我把两个句子加到一起,然后在处理,但是后面发现变慢了。。。。。
class Solution(object):
def uncommonFromSentences(self, A, B):
"""
:type A: str
:type B: str
:rtype: List[str]
"""
st = A+' '+ B
a = st.split(' ')
s = {k:0 for k in st.split(' ')}
result = []
for l in a:
s[l] += 1
for i in a:
if s[i]==1:
if i not in result:
result.append(i)
return result
我觉得是因为在合并语句时的原因,因为+对两个字符串使用,会新创建新的字符串实例,所以会慢,而且内存变大。