- Given two strings
s
andt
, returntrue
ift
is an anagram ofs
, andfalse
otherwise. - An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
- sorted()函數
將2個字串用sorted()進行排序,再比對是否一樣
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
- Counter類別
s ="anagram" t ="nagaram"
Counter(s) => Counter({'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1})
Counter(t) => Counter({'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1})
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
- Hashmap
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dicts, dictt = {},{}
for i in range(len(s)):
dicts[s[i]] = dicts.get(s[i],0) + 1
dictt[t[i]] = dictt.get(t[i],0) + 1
return dicts == dictt