Skip to content

Commit 84c8fa3

Browse files
authored
Create 2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp
1 parent 766d210 commit 84c8fa3

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class Solution {
2+
public:
3+
string smallestSubsequence(string s, int k, char letter, int repetition)
4+
{
5+
int count = 0;
6+
for (auto ch:s)
7+
{
8+
if (ch==letter)
9+
count++;
10+
}
11+
12+
int k1 = count - repetition;
13+
int k0 = s.size() - k;
14+
15+
stack<char>Stack;
16+
int count0 = 0;
17+
int count1 = 0;
18+
19+
for (int i=0; i<s.size(); i++)
20+
{
21+
if (Stack.empty()||s[i]>=Stack.top())
22+
{
23+
Stack.push(s[i]);
24+
}
25+
else if (s[i]<Stack.top())
26+
{
27+
while (!Stack.empty() && s[i]<Stack.top() && ((Stack.top()!=letter || (Stack.top()==letter && count1<k1)) && count0<k0))
28+
{
29+
if (Stack.top()==letter)
30+
count1++;
31+
count0++;
32+
Stack.pop();
33+
}
34+
Stack.push(s[i]);
35+
}
36+
}
37+
38+
39+
string result;
40+
while (!Stack.empty())
41+
{
42+
result+=Stack.top();
43+
Stack.pop();
44+
}
45+
46+
reverse(result.begin(),result.end());
47+
48+
string ans;
49+
50+
for (int i=result.size()-1; i>=0; i--)
51+
{
52+
if (count0 == k0)
53+
ans.push_back(result[i]);
54+
else
55+
{
56+
if (result[i]==letter)
57+
{
58+
if (count1 == k1)
59+
ans.push_back(result[i]);
60+
else
61+
{
62+
count0++;
63+
count1++;
64+
}
65+
}
66+
else
67+
{
68+
count0++;
69+
}
70+
}
71+
}
72+
73+
reverse(ans.begin(), ans.end());
74+
75+
return ans;
76+
77+
}
78+
};

0 commit comments

Comments
 (0)