-
Notifications
You must be signed in to change notification settings - Fork 21
/
iterative.rs
47 lines (38 loc) · 1.26 KB
/
iterative.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
pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl Solution {
pub fn shortest_to_char(s: String, c: char) -> Vec<i32> {
let c = c as u8;
let mut result = vec![0; s.len()];
let mut prev_position = i32::MIN;
for (i, (distance, x)) in (0..).zip(result.iter_mut().zip(s.bytes())) {
if x == c {
prev_position = i;
} else {
*distance = i.saturating_sub(prev_position);
}
}
prev_position = i32::MIN;
for (i, (distance, x)) in (0..).zip(result.iter_mut().zip(s.bytes()).rev()) {
if x == c {
prev_position = i;
} else {
*distance = (*distance).min(i.saturating_sub(prev_position));
}
}
result
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn shortest_to_char(s: String, c: char) -> Vec<i32> {
Self::shortest_to_char(s, c)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}