-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy path567.c
67 lines (53 loc) · 1.74 KB
/
567.c
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
const int EnglishLettersNumber = 26;
void countCharsForStringSlice(int* charsCounter, char* s, int length, int sign) {
for (int i = 0; i < length; i++) {
charsCounter[s[i] - 'a'] += sign;
}
}
// Sliding window
// Calculate number of chars in the current slide.
// Runtime: O(n)
// Space: O(1) - only number of english lowercase letters.
bool checkInclusion(char* s1, char* s2) {
int lengthS1 = strlen(s1);
int lengthS2 = strlen(s2);
if (lengthS1 > lengthS2) {
return false;
}
int* charsCounter = calloc(EnglishLettersNumber, sizeof(int));
// We keep counters of s1 with '-' sign. It has to be offset by s2 chars
countCharsForStringSlice(charsCounter, s1, lengthS1, -1);
countCharsForStringSlice(charsCounter, s2, lengthS1, 1);
int diffChars = 0;
for (int i = 0; i < EnglishLettersNumber; i++) {
if (charsCounter[i] != 0) {
diffChars++;
}
}
if (diffChars == 0) {
return true;
}
for (int i = 0; i < lengthS2 - lengthS1; i++) {
int charNumberLeft = s2[i] - 'a';
int charNumberRight = s2[i + lengthS1] - 'a';
charsCounter[charNumberLeft] -= 1;
if (charsCounter[charNumberLeft] == 0) {
diffChars -= 1;
}
else if (charsCounter[charNumberLeft] == -1) {
diffChars += 1;
}
charsCounter[charNumberRight] += 1;
if (charsCounter[charNumberRight] == 0) {
diffChars -= 1;
}
else if (charsCounter[charNumberRight] == 1) {
diffChars += 1;
}
if (diffChars == 0) {
return true;
}
}
free(charsCounter);
return false;
}