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.
中文:
給定兩個(gè)句子 A 和 B 诱建。 (句子是一串由空格分隔的單詞桂肌。每個(gè)單詞僅由小寫字母組成。)
如果一個(gè)單詞在其中一個(gè)句子中只出現(xiàn)一次瞎饲,在另一個(gè)句子中卻沒有出現(xiàn)姿鸿,那么這個(gè)單詞就是不常見的。
返回所有不常用單詞的列表。
您可以按任何順序返回列表填帽。
示例 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.
開始我是將兩句分開來處理咙好。明顯顯得很擁擠篡腌,代碼有點(diǎn)啰嗦。
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
理解還是很好理解的勾效,后面我就把兩個(gè)句子放到一起去處理了嘹悼。
2.
我把兩個(gè)句子加到一起,然后在處理层宫,但是后面發(fā)現(xiàn)變慢了杨伙。。萌腿。限匣。。
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
我覺得是因?yàn)樵诤喜⒄Z句時(shí)的原因毁菱,因?yàn)?對(duì)兩個(gè)字符串使用膛腐,會(huì)新創(chuàng)建新的字符串實(shí)例,所以會(huì)慢鼎俘,而且內(nèi)存變大。