-
Notifications
You must be signed in to change notification settings - Fork 0
/
1370.increasing-decreasing-string.cpp
51 lines (47 loc) · 1.27 KB
/
1370.increasing-decreasing-string.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
/*
* @lc app=leetcode id=1370 lang=cpp
*
* [1370] Increasing Decreasing String
*/
// @lc code=start
class Solution {
public:
string sortString(string s) {
set<char> chars;
int cnt[26];
memset(cnt, 0, sizeof(cnt));
int tot = 0;
for (char ch : s){
cnt[ch - 'a']++;
chars.insert(ch);
tot++;
}
string ans;
while(tot){
string to_remove;
for (auto it = chars.begin(); it != chars.end(); it++){
char cur = *it;
ans+=cur;
tot--;
if (--cnt[cur - 'a'] == 0)
to_remove += cur;
}
if (tot == 0)break;
for (char ch : to_remove)
chars.erase(ch);
to_remove = "";
for (auto it = chars.rbegin(); it != chars.rend(); it++){
char cur = *it;
ans+=cur;
tot--;
if (--cnt[cur - 'a'] == 0)
to_remove += cur;
}
if (tot == 0)break;
for (char ch : to_remove)
chars.erase(ch);
}
return ans;
}
};
// @lc code=end