-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathincreasing_decreasing_string.rs
More file actions
36 lines (33 loc) · 990 Bytes
/
increasing_decreasing_string.rs
File metadata and controls
36 lines (33 loc) · 990 Bytes
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
/// https://leetcode.com/problems/increasing-decreasing-string/
#[allow(clippy::needless_range_loop)]
fn sort_string(s: String) -> String {
let n = s.len();
let mut counter = [0_u8; 26];
for byte in s.into_bytes() {
counter[(byte - b'a') as usize] += 1;
}
let mut ret = Vec::with_capacity(n);
while ret.len() < n {
for i in 0..26 {
if counter[i] > 0 {
counter[i] -= 1;
ret.push(b'a' + i as u8);
}
}
for i in (0..26).rev() {
if counter[i] > 0 {
counter[i] -= 1;
ret.push(b'a' + i as u8);
}
}
}
unsafe { String::from_utf8_unchecked(ret) }
}
#[test]
fn test_sort_string() {
const TEST_CASES: [(&str, &str); 2] =
[("aaaabbbbcccc", "abccbaabccba"), ("leetcode", "cdelotee")];
for (input, output) in TEST_CASES {
assert_eq!(sort_string(input.to_string()), output.to_string());
}
}