242 Valid Anagram · LeetCode Solutions.

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 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?

Process

  • Check for the Length of both Strings.
  • Loop through the first String and store the key as char and the number of times the key is repeated as int in a Dictionary.
  • Do the same for other String.
  • Use foreach method to go through the first dictionary. In that foreach you will receive the key and value for each data in the dictionary.
  • Check whether the same Key is present in other dictionaries or not. If it is present check whether it contains the same value to this dictionary Key.
  • If everything goes well, return true else return false.

Solution for Valid Anagram

using System.Collections.Generic;
public class Solution {
    public bool IsAnagram(string s, string t) {
        var dicS = new Dictionary <char,int>();
        var dicT = new Dictionary <char,int>();
        if(s.Length != t.Length)
        {
            return false;
        }
        for(int i = 0;i< s.Length;i++)
        {
            if(dicS.ContainsKey(s[i]))
            {
                dicS[s[i]] = dicS[s[i]] + 1;
            }else{
                dicS.Add( s[i], 1);
            }
        }
        for(int j = 0;j< s.Length;j++)
        {
            if(dicT.ContainsKey(t[j]))
            {
                dicT[t[j]] = dicT[t[j]] + 1;
            }else{
                dicT.Add( t[j], 1);
            }
        }

        foreach(var x in dicS)
        {
            if(!dicT.ContainsKey(x.Key) || (dicT[x.Key] != x.Value))
            {
                return false;
            }
        }
        return true;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *