-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
81 lines (68 loc) · 1.86 KB
/
Copy pathProgram.cs
File metadata and controls
81 lines (68 loc) · 1.86 KB
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
72
73
74
75
76
77
78
79
80
using System;
class Program
{
// Driver Code
public static void Main(String[] args)
{
var test = new string[] { "eat", "tea", "tan", "ate", "nat", "bat" };
//"eat","tea","tan","ate","nat","bat"
//"eat", "tea", "tan", "ate", "nat", "bat"
var result = Solution.GroupAnagrams(test);
}
}
//IList<IList<string>> result = new List<IList<string>>();
public class Solution
{
public static IList<IList<string>> GroupAnagrams(string[] strs)
{
IList<IList<string>> result = new List<IList<string>>();
foreach(var word in strs)
{
if(result.Count == 0)
{
result.Add(new List<string>() { word });
continue;
}
var isWordAdded = false;
foreach(var setOfAnagrams in result)
{
if(isAnagrams(setOfAnagrams[0], word))
{
setOfAnagrams.Add(word);
isWordAdded = true;
break;
}
}
if (!isWordAdded)
{
result.Add(new List<string>() { word });
}
}
return result;
static bool isAnagrams(string old, string current)
{
if(old.Length != current.Length)
{
return false;
}
if(old == current)
{
return true;
}
var len = old.Length;
for (int i = 0; i < len; i++)
{
if (old.Contains(current[i]))
{
var index = old.IndexOf(current[i]);
old = old.Remove(index, 1);
}
else
{
return false;
}
}
return true;
}
}
}