-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconstruct-string-with-repeat-limit.rs
55 lines (47 loc) · 1.51 KB
/
construct-string-with-repeat-limit.rs
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
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
impl Solution {
pub fn repeat_limited_string(s: String, repeat_limit: i32) -> String {
let mut count = [0; 26];
for i in s.as_bytes() {
count[(*i - b'a') as usize] += 1;
}
let mut result = vec![];
'L: loop {
for i in (0..26).rev() {
if count[i] == 0 {
if i == 0 {
break 'L;
}
continue;
}
if count[i] <= repeat_limit {
for j in 0..count[i] {
result.push(i as u8 + b'a');
}
count[i] = 0;
continue 'L;
} else {
for j in 0..repeat_limit {
result.push(i as u8 + b'a');
}
count[i] -= repeat_limit;
let mut flag = false;
for j in (0..i).rev() {
if count[j] != 0 {
result.push(j as u8 + b'a');
count[j] -= 1;
flag = true;
continue 'L;
}
}
if !flag {
break 'L;
}
}
}
}
unsafe { String::from_utf8_unchecked(result) }
}
}