s
and t
, return true
if t
is an anagram of s
, and false
otherwise.Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
將2個字串用sorted()進行排序,再比對是否一樣
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
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)
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