-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily110.cpp
More file actions
67 lines (51 loc) · 1.65 KB
/
Copy pathdaily110.cpp
File metadata and controls
67 lines (51 loc) · 1.65 KB
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
// Solution 1 - unfinished
class Solution {
public:
bool checkInclusion(string s1, string s2) {
/*
create hashmap for s1, count of each letter
every first time we come across a common letter,
start counting until we find every letter in s1 or it's not a letter in s1
*/
if (s1.size() > s2.size())
return false;
auto s1_chars = std::vector<int>(26, 1);
for (auto& c : s1) {
s1_chars[c - 'a' + 1]++;
}
auto matching = false;
auto substr = s2.subtr(0, s1.size());
for (auto i = s1.size() - 1; i < s2.size(); ++i) {
if (substr == s1)
return true;
if (i == s1.size() - 1) {
continue;
}
substr -= s2[i - s1.size()];
substr += s2[i];
}
return false;
}
};
// Solution 2
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if (s1.length() > s2.length()) return false;
vector<int> s1Count(26, 0), s2Count(26, 0);
// Count frequencies of s1 and the first window in s2
for (int i = 0; i < s1.length(); ++i) {
s1Count[s1[i] - 'a']++;
s2Count[s2[i] - 'a']++;
}
// Slide the window over s2
for (int i = 0; i < s2.length() - s1.length(); ++i) {
if (s1Count == s2Count) return true;
// Update the window
s2Count[s2[i] - 'a']--;
s2Count[s2[i + s1.length()] - 'a']++;
}
// Check the last window
return s1Count == s2Count;
}
};