Skip to content

Latest commit

 

History

History
53 lines (40 loc) · 1.06 KB

0242. Valid Anagram.md

File metadata and controls

53 lines (40 loc) · 1.06 KB

题目

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.

我的思路

直接利用python的collections.Counter统计词频建立字典,然后判等即可。

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return collections.Counter(s) == collections.Counter(t)

网上方法:用字符的ascii码来统计词频,然后判等。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False

        alpha = [0] * 26
        beta = [0] * 26
        for c in s:
            alpha[ord(c) - 97] += 1
        for c in t:
            beta[ord(c) - 97] += 1
        return alpha == beta