0242-valid-anagram

Try it on leetcode

Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

 

Example 1:

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

Output: true

Example 2:

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

Output: false

 

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

 

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

Solution(Python)

import string
from collections import defaultdict
class Solution:
    def __init__(self):
                # 1. Generate the first 26 prime numbers
        primes = []
        num = 2
        while len(primes) < 26:
            if all(num % i != 0 for i in range(2, int(num**0.5) + 1)):
                primes.append(num)
            num += 1

        # 2. Get the lowercase alphabet letters (a-z)
        alphabet = string.ascii_lowercase

        # 3. Combine them into a dictionary
        self.letter_to_prime = dict(zip(alphabet, primes))

    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        counter = defaultdict(int)
        for i in range(len(s)):
            counter[s[i]] += 1
            counter[t[i]] -= 1
        for _,count in counter.items():
            if count < 0:
                return False
        return True
    def hashit(self, s: str, t: str) -> bool:
        return len(s) == len(t) and self.hash(s) == self.hash(t)
        
    def hash(self,s):
        hash_number = 1

        for c in s:
            hash_number *= self.letter_to_prime[c]
        return hash_number
        

Dry Run