1. 程式人生 > >LeetCode題目--有效的字母異位詞(python實現)

LeetCode題目--有效的字母異位詞(python實現)

題目

給定兩個字串 s 和 t ,編寫一個函式來判斷 t 是否是 s 的一個字母異位詞。

示例 1:

輸入: s = "anagram", t = "nagaram"
輸出: true

示例 2:

輸入: s = "rat", t = "car"
輸出: false

說明:
你可以假設字串只包含小寫字母。

進階:
如果輸入字串包含 unicode 字元怎麼辦?你能否調整你的解法來應對這種情況?

 

python程式碼實現:

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        flag = True
        data1=collections.Counter(s)
        data2 = collections.Counter(t)
        data3=(data1.keys() ^ data2.keys())
        if data3 == set() and (len(data1) !=0 or len(data2)!=0):
            data4=data1.keys()
            for key in data4:
                if key in data1.keys() and key in data2.keys():
                    if data1[key] == data2[key]:
                        flag = flag & True
                    else:
                        flag = flag & False
        elif len(data1) == 0 and len(data2) == 0:
            return True
        else:
            return False
        if flag:
            return True
        else:
            return False
        

注:

Counter類的目的是用來跟蹤值出現的次數。它是一個無序的容器型別,以字典的鍵值對形式儲存,其中元素作為key,其計數作為value