Sunday, June 2, 2024

[LeetCode] Valid Anagram

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example:

Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false

Constraints:

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


Approach: It's a simple problem to solve using hashmap. Just have a look at implementation directly.


Implementation in C#:

    public bool IsAnagram(string s, string t)
    {
        int length = s?.Length ?? 0;
        if (length != t.Length)
        {
            return false;
        }
        int[] charMap = new int[26];
        foreach (char ch in s)
        {
            ++charMap[ch - 'a'];
        }
        foreach (char ch in t)
        {
            if (charMap[ch - 'a'] == 0)
            {
                return false;
            }
            --charMap[ch - 'a'];
        }
        foreach (int i in charMap)
        {
            if (i != 0)
            {
                return false;
            }
        }
        return true;
    }

Complexity: O(n)

No comments:

Post a Comment