-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmerge-close-characters.cpp
More file actions
41 lines (39 loc) · 992 Bytes
/
merge-close-characters.cpp
File metadata and controls
41 lines (39 loc) · 992 Bytes
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
// Time: O(n + 26)
// Space: O(26)
// simulation, hash table
class Solution {
public:
string mergeCharacters(string s, int k) {
string result;
vector<int> lookup(26, -1);
for (const auto& x : s) {
if (lookup[x - 'a'] != -1 && size(result) - lookup[x - 'a'] <= k) {
continue;
}
lookup[x - 'a'] = size(result);
result.push_back(x);
}
return result;
}
};
// Time: O(n + 26)
// Space: O(26)
// simulation, freq table, two pointers
class Solution2 {
public:
string mergeCharacters(string s, int k) {
string result;
vector<int> cnt(26);
for (const auto& x : s) {
if (cnt[x - 'a']) {
continue;
}
++cnt[x - 'a'];
result.push_back(x);
if (size(result) >= k + 1) {
--cnt[result[size(result) - (k + 1)] - 'a'];
}
}
return result;
}
};