Skip to content

[242] Valid Anagram

https://leetcode.com/problems/valid-anagram/description/

  • algorithms
  • Easy (49.67%)
  • Source Code: 242.valid-anagram.py
  • Total Accepted: 323.5K
  • Total Submissions: 626.4K
  • Testcase Example: '"anagram"\n"nagaram"'

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.

Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

python
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if not s and not t: return True
        lens, lent = len(s), len(t)
        if not lens == lent: return False

        alist = [0] * 26
        blist = [0] * 26

        for i in s:
            alist[ord(i)-ord('a')] += 1

        for j in t:
            blist[ord(j)-ord('a')] += 1

        for k in range(len(alist)):
            if not alist[k] == blist[k]: return False

        return True

Last updated: