forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
increasing-decreasing-string.cpp
75 lines (70 loc) · 1.9 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Time: O(n)
// Space: O(1)
class Solution {
public:
string sortString(string s) {
string result;
auto count = counter(s);
while(result.length() != s.length()) {
for (int c = 0; c < count.size(); ++c) {
if (count[c]) {
result += ('a' + c);
--count[c];
}
}
for (int c = count.size() - 1; c >= 0; --c) {
if (count[c]) {
result += ('a' + c);
--count[c];
}
}
}
return result;
}
private:
vector<int> counter(const string& word) {
vector<int> count(26);
for (const auto& c : word) {
++count[c - 'a'];
}
return count;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
string sortString(string s) {
string result;
for (auto [count, desc] = tuple{counter(s), false}; !count.empty(); desc = !desc) {
if (!desc) {
for (auto it = begin(count); it != end(count);) {
result.push_back(it->first);
if (!--it->second) {
it = count.erase(it);
} else {
++it;
}
}
} else {
for (auto rit = rbegin(count); rit != rend(count);) {
result.push_back(rit->first);
if (!--rit->second) {
rit = reverse_iterator(count.erase(next(rit).base()));
} else {
++rit;
}
}
}
}
return result;
}
private:
map<int, int> counter(const string& word) {
map<int, int> count;
for (const auto& c : word) {
++count[c];
}
return count;
}
};