-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path567-permutation-in-string.cs
71 lines (59 loc) · 1.5 KB
/
567-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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class Solution {
public bool CheckInclusion(string s1, string s2)
{
var expectedCount = new int[26];
foreach (var ch in s1)
{
expectedCount[ch - 'a']++;
}
var currentCount = new int[26];
int aheadCount = 0, behindCount = 0;
for (var i = 0; i < 26; i++)
{
if (expectedCount[i] != 0)
{
behindCount++;
}
}
var back = 0;
for (var i = 0; i < s2.Length; i++)
{
AddChar(s2[i]);
while (back < i && aheadCount > 0)
{
RemoveChar(s2[back++]);
}
if (behindCount == 0)
{
return true;
}
}
void AddChar(char ch)
{
var i = ch - 'a';
if (currentCount[i] == expectedCount[i])
{
aheadCount++;
}
else if (currentCount[i] == expectedCount[i] - 1)
{
behindCount--;
}
currentCount[i]++;
}
void RemoveChar(char ch)
{
var i = ch - 'a';
if (currentCount[i] == expectedCount[i])
{
behindCount++;
}
else if (currentCount[i] == expectedCount[i] + 1)
{
aheadCount--;
}
currentCount[i]--;
}
return false;
}
}