异位字符串

2019-11-28  本文已影响0人  极客匠

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true
示例 2:

输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。

解题思路

  1. 利用collections.Counter(),对字符串进行计数,并存入字典中counter_s,counter_t
  2. 如果counter_s,counter_t的长度不同,则两个字符串不是异位字符串
  3. 如果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

解题二

  1. 利用collections.Counter(),对字符串进行计数,并存入字典中counter_s,counter_t
  2. 直接比较counter_s,counter_t,如果相同则返回True,反之则返回False
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return collections.Counter(s) == collections.Counter(t)

这样的计算速度更快

上一篇下一篇

猜你喜欢

热点阅读