0
点赞
收藏
分享

微信扫一扫

Leetcode 884. 两句话中的不常见单词

左手梦圆 2022-01-31 阅读 60
leetcode

原题链接:Leetcode 884. Uncommon Words from Two Sentences

A sentence is a string of single-space separated words where 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.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.

Example 1:

Input: s1 = "this apple is sweet", s2 = "this apple is sour"
Output: ["sweet","sour"]
Example 2:

Input: s1 = "apple apple", s2 = "banana"
Output: ["banana"]

Constraints:

1 <= s1.length, s2.length <= 200
s1 and s2 consist of lowercase English letters and spaces.
s1 and s2 do not have leading or trailing spaces.
All the words in s1 and s2 are separated by a single space.


思路:
找到两个字符串中只在其中一个字符串中出现的单词,只需要将两个字符串合并,然后找到里面只出现过一次的单词即可

python3做法:

class Solution:
    def uncommonFromSentences(self, A: str, B: str) -> List[str]:
        C = A.split(' ') + B.split(' ')
        return [i for i in C if C.count(i) == 1]
举报

相关推荐

0 条评论