242. Valid Anagram

Given two stringss_and_t , write a function to determine ift_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?

Thoughts:

  1. Give compare the canical sorted form
  2. Compare the char count in the map
  3. Follow-up: Method 1 would still work

Code: Sort

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

Code: Counting Map (elements in s and t needs to be hashable)

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        d = collections.defaultdict(int)
        for c in s: d[c]+= 1
        for c in t: d[c]-= 1

        return all(d[v] == 0 for v in d)

results matching ""

    No results matching ""