1. Is Anagram
(Anagram is a word or phrase formed by rearranging the letters in another word or phrase)
public static bool AreAnagrams(string str1, string
str2)
{
if (str1.Length != str2.Length)
{
return false;
}
Dictionary<char, int> charCount = new
Dictionary<char, int>();
foreach (char c in str1)
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount[c] = 1;
}
}
// Iterate through the second string and
decrease the count of each character
foreach (char c in str2)
{
if (charCount.ContainsKey(c))
{
charCount[c]--;
// If the count goes negative, they
are not anagrams
if (charCount[c] < 0)
{
return false;
}
}
}
// If all counts are 0, the strings are
anagrams
foreach (var count in charCount.Values)
{
if (count != 0)
{
return false;
}
}
return true;
}
===================================================
public static bool
AreAnagrams(string str1, string str2)
{
if (str1.Length != str2.Length)
{
return false;
}
Dictionary<char, int> map1 = new();
Dictionary<char, int> map2 = new();
for (int i = 0; i < str1.Length; i++)
{
int val1 =
map1.GetValueOrDefault(str1[i]);
map1[str1[i]] = map1.ContainsKey(str1[i]) ? ++val1 : 1;
int val2 =
map2.GetValueOrDefault(str2[i]);
map2[str2[i]] = map2.ContainsKey(str2[i]) ? ++val2 : 1;
}
if (map1.Count != map2.Count) return false;
foreach (var kvp in map1)
{
if (!map2.TryGetValue(kvp.Key, out var
value) || !value.Equals(kvp.Value))
{
return false;
}
}
return true;
}
Comments
Post a Comment