Решение на Search от Димитър Узунов

Обратно към всички решения

Към профила на Димитър Узунов

Резултати

  • 15 точки от тестове
  • 3 бонус точки
  • 18 точки общо
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)

Код

use std::collections::{HashMap, HashSet};
use std::rc::Rc;
struct WordIterator<'a> {
text: &'a str,
}
impl<'a> WordIterator<'a> {
pub fn new(text: &'a str) -> Self {
Self { text }
}
}
impl<'a> Iterator for WordIterator<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.text
.find(char::is_alphabetic)
.and_then(|word_begin| {
self.text[word_begin..]
.find(|c: char| !c.is_alphabetic())
.and_then(|end_offset| {
let word_end = word_begin + end_offset;
let result = Some(&self.text[word_begin..word_end]);
self.text = &self.text[word_end..];
result
})
.or_else(|| {
let result = Some(&self.text[word_begin..]);
self.text = "";
result
})
})
}
}
pub fn extract_words(text: &str) -> Vec<String> {
WordIterator::new(text).map(String::from).collect()
}
pub struct TextIndex {
words: HashMap<String, HashSet<Rc<String>>>,
}
impl TextIndex {
pub fn new() -> Self {
Self { words: HashMap::new() }
}
pub fn push(&mut self, text: &str) {
let text_rc = Rc::new(String::from(text));
for word in extract_words(text) {
self.words
.get_mut(&word)
.and_then(|text_set| Some(text_set.insert(Rc::clone(&text_rc))))
.or_else(|| {
let mut text_set = HashSet::new();
text_set.insert(Rc::clone(&text_rc));
self.words.insert(word, text_set);
Some(true)
});
}
}
pub fn search(&self, query: &str) -> HashSet<&str> {
WordIterator::new(query)
.filter_map(|word| self.words.get(word))
.flat_map(|text_set| text_set)
.map(|text| text.as_str())
.collect()
}
}

Лог от изпълнението

Compiling solution v0.1.0 (file:///tmp/d20180105-6053-1kex0rh/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 12.41 secs
     Running target/debug/deps/solution-3f98bfa5c86a5dd9

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-3d9e4ea2eafbbc82

running 5 tests
test solution_test::test_extract_words_basic ... ok
test solution_test::test_extract_words_extra ... ok
test solution_test::test_search_multiple_words ... ok
test solution_test::test_search_special_cases ... ok
test solution_test::test_search_word ... ok

test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

История (1 версия и 1 коментар)