forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmallest K-Length Subsequence With Occurrences of a Letter.cpp
55 lines (55 loc) · 1.32 KB
/
Smallest K-Length Subsequence With Occurrences of a Letter.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
class Solution {
public:
string smallestSubsequence(string s, int k, char letter, int repetition) {
int count=0, inStack=0;
int n=s.size();
for(int i=0; i<n; i++)
if(s[i]==letter)
count++;
string res="";
int i=0;
while(i<n) {
if(res.empty())
res.push_back(s[i]);
else {
while(!res.empty() && res.back()>s[i] && n-i+res.size()>k) {
if(res.back()==letter && count+inStack-1>=repetition) {
res.pop_back();
inStack--;
}
else if(res.back()==letter)
break;
else
res.pop_back();
}
if(s[i]==letter) {
inStack++;
count--;
}
res.push_back(s[i]);
}
i++;
}
string ret="";
for(int i=0;i<res.size();i++)
{
if(res[i]==letter && repetition>0 && k>0)
{
repetition--;
ret+=res[i];
k--;
}
else if(k-repetition>0)
{
k--;
ret+=res[i];
}
}
return ret;
}
};
/*
if(find helpful) {
do upvote(); // thanks
}
*/