Skip to content

Commit 9fea5bd

Browse files
authored
Merge pull request neetcode-gh#1465 from sarangbg/main
Create: 438-find-all-anagrams-in-a-string.cs
2 parents 0e30041 + c19b2f3 commit 9fea5bd

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
public class Solution
2+
{
3+
4+
public IList<int> FindAnagrams(string s, string p)
5+
{
6+
List<int> res = new List<int>();
7+
8+
int pSize = p.Length;
9+
int sSize = s.Length;
10+
11+
if (pSize > sSize)
12+
{
13+
return res;
14+
}
15+
16+
Dictionary<char, int> pHash = new Dictionary<char, int>();
17+
Dictionary<char, int> sHash = new Dictionary<char, int>();
18+
19+
foreach (char c in p)
20+
{
21+
int tmp;
22+
pHash.TryGetValue(c, out tmp);
23+
pHash[c] = tmp + 1;
24+
}
25+
26+
for (int x = 0; x < pSize; x++)
27+
{
28+
char c = s[x];
29+
int tmp;
30+
sHash.TryGetValue(c, out tmp);
31+
sHash[c] = tmp + 1;
32+
}
33+
34+
if (compareDict(pHash, sHash))
35+
{
36+
res.Add(0);
37+
}
38+
39+
int i = 1;
40+
int j = i + pSize - 1;
41+
42+
while (j < sSize)
43+
{
44+
sHash[s[i - 1]]--;
45+
46+
int tmp;
47+
sHash.TryGetValue(s[j], out tmp);
48+
sHash[s[j]] = tmp + 1;
49+
50+
if (compareDict(pHash, sHash))
51+
{
52+
res.Add(i);
53+
}
54+
55+
i++;
56+
j++;
57+
}
58+
59+
return res;
60+
}
61+
62+
public bool compareDict(Dictionary<char, int> d1, Dictionary<char, int> d2)
63+
{
64+
foreach (var i in d1)
65+
{
66+
if (d2.ContainsKey(i.Key) && i.Value == d2[i.Key])
67+
{
68+
continue;
69+
}
70+
else
71+
{
72+
return false;
73+
}
74+
}
75+
76+
return true;
77+
}
78+
}

0 commit comments

Comments
 (0)