Skip to content

Commit 0da785e

Browse files
authored
Create increasing-decreasing-string.cpp
1 parent 6d86603 commit 0da785e

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

C++/increasing-decreasing-string.cpp

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string sortString(string s) {
7+
string result;
8+
auto count = counter(s);
9+
while(result.length() != s.length()) {
10+
for (int c = 0; c < count.size(); ++c) {
11+
if (count[c]) {
12+
result += ('a' + c);
13+
--count[c];
14+
}
15+
}
16+
for (int c = count.size() - 1; c >= 0; --c) {
17+
if (count[c]) {
18+
result += ('a' + c);
19+
--count[c];
20+
}
21+
}
22+
}
23+
return result;
24+
}
25+
26+
private:
27+
vector<int> counter(const string& word) {
28+
vector<int> count(26);
29+
for (const auto& c : word) {
30+
++count[c - 'a'];
31+
}
32+
return count;
33+
}
34+
};
35+
36+
37+
// Time: O(n)
38+
// Space: O(1)
39+
class Solution2 {
40+
public:
41+
string sortString(string s) {
42+
string result;
43+
for (auto [count, desc] = tuple{counter(s), false}; !count.empty(); desc = !desc) {
44+
if (!desc) {
45+
for (auto it = begin(count); it != end(count);) {
46+
result.push_back(it->first);
47+
if (!--it->second) {
48+
it = count.erase(it);
49+
} else {
50+
++it;
51+
}
52+
}
53+
} else {
54+
for (auto rit = rbegin(count); rit != rend(count);) {
55+
result.push_back(rit->first);
56+
if (!--rit->second) {
57+
rit = reverse_iterator(count.erase(next(rit).base()));
58+
} else {
59+
++rit;
60+
}
61+
}
62+
}
63+
}
64+
return result;
65+
}
66+
67+
private:
68+
map<int, int> counter(const string& word) {
69+
map<int, int> count;
70+
for (const auto& c : word) {
71+
++count[c];
72+
}
73+
return count;
74+
}
75+
};

0 commit comments

Comments
 (0)