Leetcode 1370. Increasing Decreasing String
Given a string s
, you need to sort it in the following order:
s
which has not been picked yet. Append it to the result.s
which has not been picked yet and append it to the result.s
.s
which has not been picked yet. Append it to the result.s
which has not been picked yet and append it to the result.s
.You should combine the result of these steps to form the final resultant string.
s
guaranteed to be non-empty?Assuming:
s
contains only lowercase English letters.s
is of reasonable length to fit within typical problem constraints on competitive programming platforms.#include <string>
#include <vector>
std::string sortString(const std::string& s) {
std::vector<int> charCount(26, 0);
for(char c : s) {
charCount[c - 'a']++;
}
std::string result;
bool ascending = true;
while(result.size() < s.size()) {
if (ascending) {
for (int i = 0; i < 26; ++i) {
if (charCount[i] > 0) {
result.push_back('a' + i);
charCount[i]--;
}
}
} else {
for (int i = 25; i >= 0; --i) {
if (charCount[i] > 0) {
result.push_back('a' + i);
charCount[i]--;
}
}
}
ascending = !ascending;
}
return result;
}
s
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?