forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0567.cpp
More file actions
81 lines (64 loc) · 1.71 KB
/
0567.cpp
File metadata and controls
81 lines (64 loc) · 1.71 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//Solution 1:-
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if (s1.length() > s2.length())
return false;
std::vector<int> target(26), f(26);
int k{int(s1.length())};
for (int i{0}; i < k; i++) {
target[s1[i] - 'a']++;
f[s2[i] - 'a']++;
}
if (f == target)
return true;
int n{int(s2.length())};
for (int i{1}; i + k - 1 < n; i++) {
f[s2[i + k - 1] - 'a']++;
f[s2[i - 1] - 'a']--;
if (f == target)
return true;
}
return false;
}
};
//Solution 2:-
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if(s1.length() > s2.length())
return false;
vector<int> chars(26, 0);
for(auto c : s1)
chars[c - 'a']++;
for(int i = 0; i < s1.length(); i++)
chars[s2[i] - 'a']--;
bool found = true;
for(auto c : chars){
if(c != 0){
found = false;
break;
}
}
if(found)
return true;
int start = 1;
while(start <= s2.length() - s1.length()){
int pos1 = s2[start - 1] - 'a';
int pos2 = s2[start + s1.length() - 1] - 'a';
chars[pos1]++;
chars[pos2]--;
found = true;
for(auto c : chars){
if(c != 0){
found = false;
break;
}
}
if(found)
return true;
start++;
}
return false;
}
};