给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
解题思路
- 利用collections.Counter(),对字符串进行计数,并存入字典中counter_s,counter_t
- 如果counter_s,counter_t的长度不同,则两个字符串不是异位字符串
- 如果counter_s,counter_t的长度相同,则遍历s,通过判断counter_s,counter_t的每个字符的数量是否相等,如果每个字符的数量都相同,则是异位字符串,反之则不是
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
counter_s = collections.Counter(s)
counter_t = collections.Counter(t)
if(len(counter_s) != len(counter_t)):
return False
for c in s:
if counter_s[c] != counter_t[c]:
return False
return True
解题二
- 利用collections.Counter(),对字符串进行计数,并存入字典中counter_s,counter_t
- 直接比较counter_s,counter_t,如果相同则返回True,反之则返回False
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return collections.Counter(s) == collections.Counter(t)
这样的计算速度更快
网友评论