leetcode_884_两句话中的不常见单词_e

English:

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:

  1. 0 <= A.length <= 200
  2. 0 <= B.length <= 200
  3. A and B 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
image.png

我觉得是因为在合并语句时的原因,因为+对两个字符串使用,会新创建新的字符串实例,所以会慢,而且内存变大。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,183评论 0 10
  • 本文转载自知乎 作者:季子乌 笔记版权归笔记作者所有 其中英文语句取自:英语流利说-懂你英语 —————————...
    Danny_Edward阅读 13,888评论 1 24
  • var navigator = navigator || {};var window = window || {}...
    DF_Sky阅读 5,148评论 0 0
  • 我在电话里噼里啪啦地抱怨许久,妈妈听我渐渐平静下来才慢慢地说:“朋友不是轻易就能交到的,你用心经营一段友情并没有错...
    聪六六阅读 2,900评论 0 0
  • 变穷的方式有很多,车祸、大病、赌博、吸毒,这些都是由悲剧引发的变穷。而在中国农村,还有一种充满喜庆色彩的变穷方式—...
    westeRR阅读 4,218评论 0 2

友情链接更多精彩内容