天天看點

242. 有效的字母異位詞(Python)

一.題目

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

示例 1:

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

示例 2:

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

說明:

你可以假設字元串隻包含小寫字母。

進階:

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

二.思路和代碼

1.為每個字元串建立hash table,然後循環某字元串,如果某一個元素同時也在另一個字元串裡,那麼同時删除兩個哈希表的這一項。最後判斷兩個hash table 是否都為空。運作時間有點長,但可以過。

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        else:
            hash_table_s = {}
            hash_table_t = {}
            for i in s:
                if ord(i) in hash_table_s:
                    hash_table_s[ord(i)] += 1
                else:
                    hash_table_s[ord(i)] = 1
                    
            for j in t:
                if ord(j) in hash_table_t:
                    hash_table_t[ord(j)] += 1
                else:
                    hash_table_t[ord(j)] = 1
                    
            for c in s:
                if ord(c) in hash_table_t:
                    if hash_table_s[ord(c)] == 1:
                        hash_table_s.pop(ord(c))
                    else:
                        hash_table_s[ord(c)] -= 1
                        
                    if hash_table_t[ord(c)] == 1:
                        hash_table_t.pop(ord(c))
                    else:
                        hash_table_t[ord(c)] -= 1
                        
        if hash_table_s == {} and hash_table_t == {}:
            return True
        else:
            return False 
           

2. 使用題目内部邏輯構造判斷語句:對于字母異位詞我們可以看出有兩個條件可以限定,第一是兩串字元串出現的字母相同,第二是這些字母出現的次數相同。

對于第一個限定條件可以用set()來解決;第二個限定條件可以使用字元串的count() 方法。

return (set(s) == set(t) and all(s.count(i) == t.count(i) for i in set(s)))
           

all() 函數用于判斷給定的可疊代參數 iterable 中的所有元素是否都為True,如果是傳回 True,否則傳回 False (傳回的是一個bool值)。與之對應的的還有any(): 隻要可疊代參數iterable有一個是True那麼就傳回True。

元素除了是 0、空、FALSE 外都算True。

From:http://www.runoob.com/python/python-func-all.html