一.題目
給定兩個字符串 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。