[leetcode] 884. Uncommon Words from Two Sentences

网友投稿 673 2022-08-23

[leetcode] 884. Uncommon Words from Two Sentences

[leetcode] 884. Uncommon Words from Two Sentences

Description

We are given two sentences A and B. (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 <= 2000 <= B.length <= 200A and B both contain only spaces and lowercase letters.

分析

题目的意思是:给定两个句子,找出其中的uncommon的句子。这道题换句话说找出词频为1的单词,如果想到这个就很好了,我看标准解答直接用一个字典统计词频然后把词频为1的找出来就行了。

我的解法有点中规中矩,用了两个字典,分别统计词频,然后取出词频为1的单词,相比于标准答案稍稍复杂了一点,哈哈哈。

代码

class Solution: def uncommonFromSentences(self, A: str, B: str) -> List[str]: dA=defaultdict(int) dB=defaultdict(int) arrA=A.split() arrB=B.split() for item in arrA: dA[item]+=1 for item in arrB: dB[item]+=1 res=[] for k,v in dA.items(): if(v==1 and k not in dB): res.append(k) for k,v in dB.items(): if(v==1 and k not in dA): res.append(k) return res

参考文献

​​solution​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:一个Android项目搞定所有主流架构
下一篇:牛课网 python 最长公共子序列和最长公共子串的问题(不太懂)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~