給定兩個字符串 s 和 t ,編寫一個函數來判斷 t 是否是 s 的一個字母異位詞。
示例 1:
輸入: s = "anagram", t = "nagaram"
輸出: true
示例 2:
輸入: s = "rat", t = "car"
輸出: false
說明:
你可以假設字符串只包含小寫字母。
進階:
如果輸入字符串包含 unicode 字符怎么辦?你能否調整你的解法來應對這種情況?
思路
我的第一個思路是對這兩個字符串排序,如果兩個排序后的結果是一樣的,那么就是其中一個就是另外一個的字母異位詞
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s)==sorted(t)
這個代碼思路很清晰,實現也很簡單,但是sorted的效率沒有這么理想,提交后只超過了36%左右的評測-_-||,不過它的直觀與優美很讓人滿意哈哈哈哈哈
看下排第一個的代碼是
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(t) != len(s):
return False
c = set(t)
for i in c:
if t.count(i) != s.count(i):
return False
return True
先比較長度應該就可以過一些數據了,然后因為是逐個字母檢查的所以一旦發現不符合就可以退出來,效率得到了不少提升