C# solution using dictionary


  • 1
    B
    public class Solution {
      	public bool IsAnagram(string s, string t)
      	{
      		if (s.Length != t.Length) return false;
            
            // Initializing hash to store letter counts  		
      		Dictionary<char, int> anagram = new Dictionary<char, int>();
      		
      		// Filling the hash with first string letter counts
      		for (int i = 0; i < s.Length; i++)
      		{
      			if (anagram.ContainsKey(s[i]))
      			{
      				anagram[s[i]]++;
      			}
      			else
      			{
      				anagram.Add(s[i], 1);
      			}
      		}
      		
      		// Loop through second string, decrementing all similar values
      		for (int i = 0; i < t.Length; i++)
      		{
      			if (anagram.ContainsKey(t[i])) anagram[t[i]]--;
      		}
      		
      		// Loop through hash, if the value is non-zero, it is not an anagram
      		foreach (KeyValuePair<char, int> entry in anagram)
      		{
      			if (entry.Value != 0) return false;
      		}
      		
      		return true;
      	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.