forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
51 lines (38 loc) · 1.17 KB
/
main2.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
/// Source : https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/
/// Author : liuyubobobo
/// Time : 2019-07-07
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/// Two Pointers and use a unordered_set to record all repeats characters
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int numKLenSubstrNoRepeats(string S, int K) {
if(S.size() < K) return 0;
vector<int> freq(26, 0);
unordered_set<char> repeats;
for(int i = 0; i < K - 1; i ++){
freq[S[i] - 'a'] ++;
if(freq[S[i] - 'a'] > 1)
repeats.insert(S[i]);
}
int res = 0;
for(int i = K - 1; i < S.size(); i ++){
freq[S[i] - 'a'] ++;
if(freq[S[i] - 'a'] > 1) repeats.insert(S[i]);
if(!repeats.size()) res ++;
freq[S[i - (K - 1)] - 'a'] --;
if(freq[S[i - (K - 1)] - 'a'] <= 1)
repeats.erase(S[i - (K - 1)]);
}
return res;
}
};
int main() {
cout << Solution().numKLenSubstrNoRepeats("havefunonleetcode", 5) << endl;
// 6
return 0;
}