思路
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
提示:
1 <= s.length, t.length <= 5 * 104
s 和 t 仅包含小写字母
解题方法
复杂度
时间复杂度:
空间复杂度:
代码
解法一:
class solution(object):
def isanagram(self, s, t):
if len(s) != len(t):
return false
count_s = {}
for char in s:
count_s[char] = count_s.get(char,0) + 1
count_t = {}
for char in t:
count_t[char] = count_t.get(char,0) + 1
return count_s == count_t
解法二:
class solution(object):
def isanagram(self, s, t):
if len(s) != len(t):
return false
count = {}
for char in s:
count[char] = count.get(char,0) + 1
for char in t:
if char not in count:
return false
count[char] -= 1
if count[char] < 0:
return false
return true
时间复杂度为 o(n),其中n是字符串s和t的长度的较大值。
空间复杂度为 o(1)。
解法三:
进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
- 可以使用 python 中的 collections.counter 类来统计每个字符的出现次数,这样可以更好地处理 unicode 字符。counter 类可以接受任何可迭代对象作为输入,包括 unicode 字符串。
from collections import counter
class solution(object):
def isanagram(self, s, t):
if len(s) != len(t):
return false
counter_s = counter(s)
counter_t = counter(t)
return counter_s == counter_t
发表评论