/
sliding_window.rs
94 lines (74 loc) · 2.28 KB
/
sliding_window.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl Solution {
pub fn balanced_string(s: String) -> i32 {
let s = s.as_bytes();
let mut q_count = 0;
let mut w_count = 0;
let mut e_count = 0;
let mut r_count = 0;
for &c in s {
match c {
b'Q' => q_count += 1,
b'W' => w_count += 1,
b'E' => e_count += 1,
_ => r_count += 1,
}
}
let n = s.len();
let limit = n / 4;
let mut invalid = u8::from(q_count > limit)
+ u8::from(w_count > limit)
+ u8::from(e_count > limit)
+ u8::from(r_count > limit);
if invalid == 0 {
0
} else {
let mut start = 0;
let mut end = 0;
let mut result = n;
for &c in s {
let count = match c {
b'Q' => &mut q_count,
b'W' => &mut w_count,
b'E' => &mut e_count,
_ => &mut r_count,
};
*count -= 1;
if *count == limit {
invalid -= 1;
}
end += 1;
while invalid == 0 {
result = result.min(end - start);
let old = s[start];
let count = match old {
b'Q' => &mut q_count,
b'W' => &mut w_count,
b'E' => &mut e_count,
_ => &mut r_count,
};
if *count == limit {
invalid += 1;
}
*count += 1;
start += 1;
}
}
result as _
}
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn balanced_string(s: String) -> i32 {
Self::balanced_string(s)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}