- Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathPermutation-In-String.cpp
59 lines (47 loc) · 1.39 KB
/
Permutation-In-String.cpp
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
classSolution {
public:
boolcheck(vector<int>& diff){
for (int i = 0; i < 26; i++)
if (diff[i] != 0) returnfalse;
returntrue;
}
boolcheckInclusion(string s1, string s2) {
int n = s2.length();
int m = s1.length();
if (m > n) returnfalse;
vector<int> diff(26, 0);
for (int i = 0; i < m; i++) {
diff[s2[i] - 'a']++;
diff[s1[i] - 'a']--;
}
vector<int> ans;
if (check(diff)) returntrue;
for (int i = m; i < n; i++){
diff[s2[i] - 'a']++;
diff[s2[i-m]-'a']--;
if (check(diff)) returntrue;
}
returnfalse;
}
};
classSolution2 {
public:
boolcheckInclusion(string s1, string s2) {
vector<int> h1(26,0);
int count = s1.size();
int right = 0, left = 0;
int l_idx;
for (char &c : s1) ++h1[c-'a'];
for (int right = 0; right < s2.size() ; ++right) {
count -= h1[s2[right]-'a']-- > 0;
if (count == 0) {
l_idx = right - s1.size() + 1;
for (; left < l_idx; ++left)
count += h1[s2[left]-'a']++ >= 0;
if (count == 0)
returntrue;
}
}
returnfalse;
}
};