-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0438-find-all-anagrams-in-a-string.cs
78 lines (63 loc) · 1.61 KB
/
0438-find-all-anagrams-in-a-string.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
72
73
74
75
76
77
78
public class Solution
{
public IList<int> FindAnagrams(string s, string p)
{
List<int> res = new List<int>();
int pSize = p.Length;
int sSize = s.Length;
if (pSize > sSize)
{
return res;
}
Dictionary<char, int> pHash = new Dictionary<char, int>();
Dictionary<char, int> sHash = new Dictionary<char, int>();
foreach (char c in p)
{
int tmp;
pHash.TryGetValue(c, out tmp);
pHash[c] = tmp + 1;
}
for (int x = 0; x < pSize; x++)
{
char c = s[x];
int tmp;
sHash.TryGetValue(c, out tmp);
sHash[c] = tmp + 1;
}
if (compareDict(pHash, sHash))
{
res.Add(0);
}
int i = 1;
int j = i + pSize - 1;
while (j < sSize)
{
sHash[s[i - 1]]--;
int tmp;
sHash.TryGetValue(s[j], out tmp);
sHash[s[j]] = tmp + 1;
if (compareDict(pHash, sHash))
{
res.Add(i);
}
i++;
j++;
}
return res;
}
public bool compareDict(Dictionary<char, int> d1, Dictionary<char, int> d2)
{
foreach (var i in d1)
{
if (d2.ContainsKey(i.Key) && i.Value == d2[i.Key])
{
continue;
}
else
{
return false;
}
}
return true;
}
}