forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0567-permutation-in-string.cs
56 lines (48 loc) · 1.45 KB
/
0567-permutation-in-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
public class Solution
{
public bool CheckInclusion(string s1, string s2)
{
{
if (s1.Length > s2.Length) return false;
var s1Count = Enumerable.Repeat(0, 26).ToArray();
var s2Count = Enumerable.Repeat(0, 26).ToArray();
for (var i = 0; i < s1.Length; i++)
{
s1Count[s1[i] - 'a']++;
s2Count[s2[i] - 'a']++;
}
var matches = 0;
for (var i = 0; i < 26; i++)
{
if (s1Count[i] == s2Count[i]) matches++;
}
var left = 0;
for (var right = s1.Length; right < s2.Length; right++)
{
if (matches == 26) return true;
var index = s2[right] - 'a';
s2Count[index]++;
if (s1Count[index] == s2Count[index])
{
matches++;
}
else if (s1Count[index] + 1 == s2Count[index])
{
matches--;
}
index = s2[left] - 'a';
s2Count[index]--;
if (s1Count[index] == s2Count[index])
{
matches++;
}
else if (s1Count[index] - 1 == s2Count[index])
{
matches--;
}
left++;
}
return matches == 26;
}
}
}