Leetcode初级算法 有效的字母异位词(Python)

问题描述:

算法思路:

意思就是判断第二个字符串是不是第一个字符串打乱的结果,从两方面比较:字符串长度和每个字符出现的字数。注意比较次数是用内置的字符串方法count(),使代码更简洁。

代码:

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        chars = set(s)
        for char in chars:
            if s.count(char) != t.count(char):
                return False
        return True

猜你喜欢

转载自blog.csdn.net/weixin_42095500/article/details/83143322
今日推荐