当前位置:网站首页>884. Uncommon words in two sentences

884. Uncommon words in two sentences

2022-07-05 05:42:00 A big pigeon

topic : Enter two sentences , Return to the list of uncommon words in two sentences .

“ Uncommon words ” It means to appear only once in a sentence , And another sentence did not appear .

Explain : Directly according to the meaning of the topic , Please appear only once in a sentence , And another word that doesn't appear . use Counter() Count times .

class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        tokens1 = s1.split()
        tokens2 = s2.split()
        ans = []
        cnt1 = Counter(tokens1)
        cnt2 = Counter(tokens2)
        #print(cnt1,cnt2)
        for k, v in cnt1.items():
            if v == 1 and k not in cnt2:
                ans.append(k)
        for k, v in cnt2.items():
            if v == 1 and k not in cnt1:
                ans.append(k)  
        return ans    

To simplify the , Appear once in a sentence , Another sentence does not appear , That's the same thing as being in s1+s2 There is one occurrence in total .

    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        s = s1+" "+s2
        tokens = s.split()
        ans = []
        cnt = Counter(tokens)
        for k, v in cnt.items():
            if v == 1 :
                ans.append(k)
        return ans 

 

原网站

版权声明
本文为[A big pigeon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140620422440.html