-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrintAnagramsInArray.cs
71 lines (52 loc) · 1.59 KB
/
PrintAnagramsInArray.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections;
using System.Collections.Generic;
// To execute C#, please define "static void Main" on a class
// named Solution.
class Solution
{
static void Main(string[] args)
{
string[] words = new string[] { "cat", "dog", "tac", "god", "act" };
FindAnagrams f = new FindAnagrams();
f.PrintAnagrams(words);
}
}
public class FindAnagrams
{
public void PrintAnagrams(string[] words)
{
int length = words.Length;
if(length == 0)
return;
Dictionary<int, List<string>> map = new Dictionary<int, List<string>>();
for(int i=0; i<length; i++)
{
string word = words[i];
char[] letters = word.ToCharArray();
Array.Sort(letters);
string newword = new string(letters);
int key = newword.GetHashCode();
if(map.ContainsKey(key))
{
List<string> wds = map[key];
wds.Add(word);
map.Remove(key);
map.Add(key, wds);
}
else
{
List<string> wds = new List<string>();
wds.Add(word);
map.Add(key, wds);
}
}
foreach(var kvp in map)
{
foreach(var wd in kvp.Value)
{
Console.Write(wd + " ");
}
}
}
}