Input:
s = "aaaabbbbcccc"
Output:
"abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
Example 2:
1
2
3
4
5
Input:
s = "rat"
Output:
"art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
The key idea is to simulate the process by repeatedly picking the smallest and then the largest available characters, using a frequency array to efficiently track which characters remain. This allows us to build the answer in the required order without repeatedly sorting.
classSolution {
public: string sortString(string s) {
vector<int> cnt(26, 0);
for (char c : s) cnt[c -'a']++;
string ans;
int n = s.size();
while (ans.size() < n) {
for (int i =0; i <26; ++i) {
if (cnt[i]) {
ans += (char)('a'+ i);
cnt[i]--;
}
}
for (int i =25; i >=0; --i) {
if (cnt[i]) {
ans += (char)('a'+ i);
cnt[i]--;
}
}
}
return ans;
}
};
classSolution {
public String sortString(String s) {
int[] cnt =newint[26];
for (char c : s.toCharArray()) cnt[c -'a']++;
StringBuilder ans =new StringBuilder();
int n = s.length();
while (ans.length() < n) {
for (int i = 0; i < 26; ++i) {
if (cnt[i]> 0) {
ans.append((char)('a'+ i));
cnt[i]--;
}
}
for (int i = 25; i >= 0; --i) {
if (cnt[i]> 0) {
ans.append((char)('a'+ i));
cnt[i]--;
}
}
}
return ans.toString();
}
}
classSolution {
funsortString(s: String): String {
val cnt = IntArray(26)
for (c in s) cnt[c - 'a']++val ans = StringBuilder()
val n = s.length
while (ans.length < n) {
for (i in0..25) {
if (cnt[i] > 0) {
ans.append('a' + i)
cnt[i]-- }
}
for (i in25 downTo 0) {
if (cnt[i] > 0) {
ans.append('a' + i)
cnt[i]-- }
}
}
return ans.toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defsortString(self, s: str) -> str:
cnt: list[int] = [0] *26for c in s:
cnt[ord(c) - ord('a')] +=1 ans: list[str] = []
n: int = len(s)
while len(ans) < n:
for i in range(26):
if cnt[i]:
ans.append(chr(ord('a') + i))
cnt[i] -=1for i in range(25, -1, -1):
if cnt[i]:
ans.append(chr(ord('a') + i))
cnt[i] -=1return''.join(ans)
impl Solution {
pubfnsort_string(s: String) -> String {
letmut cnt = [0; 26];
for b in s.bytes() {
cnt[(b -b'a') asusize] +=1;
}
let n = s.len();
letmut ans = Vec::with_capacity(n);
while ans.len() < n {
for i in0..26 {
if cnt[i] >0 {
ans.push((b'a'+ i asu8) aschar);
cnt[i] -=1;
}
}
for i in (0..26).rev() {
if cnt[i] >0 {
ans.push((b'a'+ i asu8) aschar);
cnt[i] -=1;
}
}
}
ans.into_iter().collect()
}
}