leetcode-5.12[263. 醜數、884. 兩句話中的不常見單詞、929. 獨特的電子郵件地址](python實現)

題目1

在這裏插入圖片描述

題解1

class Solution:
    def isUgly(self, num: int) -> bool:
        """
            貪心算法
        """
        #     if num < 1:
        #         return False
        #     while num % 2 == 0:
        #         num /= 2
        #     while num % 3 == 0:
        #         num /= 3
        #     while num % 5 == 0:
        #         num /= 5
        #    return num == 1


        while (num > 1) and (num%2==0 or num%3==0 or num%5==0):
            if num%2 == 0:
               num /= 2
            if num%3 == 0:
                num /= 3
            if num%5 == 0:
                num /= 5
        return num == 1

題目2

在這裏插入圖片描述

附上題目鏈接

題解2

class Solution:
    def uncommonFromSentences(self, A: str, B: str) -> List[str]:
        from collections import Counter
        # 過濾出現多次(>1)的單詞
        countA = Counter(A.split())
        countB = Counter(B.split())
        setA = set([key for key in countA if countA[key] > 1])
        setB = set([key for key in countB if countB[key] > 1])
        # 求差集
        count = set(A.split())^set(B.split())
        # 過濾在次數超過兩次的單詞
        count = count - setA - setB
        return count

附上題目鏈接

題目3

在這裏插入圖片描述

題解3

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        res=set()
        for email in emails:
            # 分隔本地名稱和域名
            local,domain=email.split('@')

            idx=local.find('+')
            if idx==-1:
                idx=len(local)
            # 如果有加號去掉+之前的. ,否則去掉整個本地名稱的.
            ls=local[:idx].split('.')
            res.add(''.join(ls)+'@'+domain)

        return len(res)

附上題目鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章