-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmallestSubsequence.cpp
More file actions
30 lines (30 loc) · 987 Bytes
/
smallestSubsequence.cpp
File metadata and controls
30 lines (30 loc) · 987 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
class Solution {
public:
string smallestSubsequence(string s, int k, char letter, int repetition) {
if (k == s.size()) return s;
if (k == repetition) return string(repetition, letter);
string ans(s.size(), 'a');
int letterToDel = std::count(s.begin(), s.end(), letter) - repetition, toDel = s.size() - k, j = 0;
for (int i = 0; i < s.size(); i++) {
while(j && toDel && ans[j-1] > s[i]) {
if (ans[j-1] == letter) {
if (!letterToDel) break;
else letterToDel--;
}
toDel--;
j--;
}
ans[j++] = s[i];
}
while (j >= k) {
if (ans[j--] == letter) letterToDel--;
}
for (j = k - 1; letterToDel < 0; j--) {
if (ans[j] != letter) {
ans[j] = letter;
letterToDel++;
}
}
return ans.substr(0, k);
}
};