Skip to content

Instantly share code, notes, and snippets.

@AnthonyMikh
Created May 3, 2020 17:02
Show Gist options
  • Save AnthonyMikh/185832a19bdd851b6fca6f2c113743c4 to your computer and use it in GitHub Desktop.
Save AnthonyMikh/185832a19bdd851b6fca6f2c113743c4 to your computer and use it in GitHub Desktop.
Решение задачи с Хабра от @Milein: найти максимальное количество идущих подряд символов для каждого сивола строки
fn cut_repeating_prefix(source: &str) -> Option<(char, usize, &str)> {
let mut chars = source.char_indices();
let first = chars.next()?.1;
let len = chars
.find_map(|(i, ch)| if ch != first { Some(i) } else { None })
.unwrap_or(source.len());
let count = len / first.len_utf8();
let (_pre, post) = source.split_at(len);
Some((first, count, post))
}
use std::collections::HashMap;
fn max_repeating(mut s: &str) -> HashMap<char, usize> {
let mut lens = HashMap::new();
let counts = std::iter::from_fn(|| {
let (ch, count, rest) = cut_repeating_prefix(s)?;
s = rest;
Some((ch, count))
});
for (ch, count) in counts {
let max = lens.entry(ch).or_insert(0);
*max = (*max).max(count);
}
lens
}
fn main() {
println!("{:?}", max_repeating("abbb"));
println!("{:?}", max_repeating("аяяя"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment