leetcode 242. Valid Anagram(python)

422 阅读1分钟

描述

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:

You may assume the string contains only lowercase alphabets.

解析

根据题意,因为包含的都是小写字母,所以遍历 26 个英文字母,只要长度相同,且 s 和 t 中包含的每个字母数量一样即为 True ,否则为 False 。

解答

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s)!=len(t):
            return False
        for c in range(ord('a'),ord('z')+1):
            if s.count(chr(c)) != t.count(chr(c)):
                return False
        return True

运行结果

Runtime: 16 ms, faster than 99.96% of Python online submissions for Valid Anagram.
Memory Usage: 14 MB, less than 96.12% of Python online submissions for Valid Anagram..		
	

解析

根据题意,判断 s 和 t 的包含的字母完全一样即可,可以使用 collections.Counter 内置方法直接计算,判断结果是否相等即可。

解答

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return collections.Counter(s)==collections.Counter(t)	

运行结果

Runtime: 52 ms, faster than 32.64% of Python online submissions for Valid Anagram.
Memory Usage: 14.2 MB, less than 69.42% of Python online submissions for Valid Anagram..

原题链接:leetcode.com/problems/va…

您的支持是我最大的动力