Ad
Code
Diff
  • fn find_the_longest_word(sentence: &str) -> Option<&str> {
        let words: Vec<&str> = sentence.split_whitespace().collect();
        let max_len = words.iter().map(|word| word.len()).max()?;
    
        let longest_words: Vec<&str> = words.into_iter().filter(|&word| word.len() == max_len).collect();
    
        if longest_words.len() > 1 {
            None
        } else {
            longest_words.get(0).copied()
        }
    }
    • fn find_the_longest_word(sentence: &str) -> Option<&str> {
    • let max_len = sentence.split_whitespace().map(str::len).max()?;
    • let mut max_words = sentence.split_whitespace().filter(|word| word.len() == max_len);
    • let first_max = max_words.next();
    • let second_max = max_words.next();
    • if second_max.is_some() {
    • return None;
    • }
    • first_max
    • }
    • let words: Vec<&str> = sentence.split_whitespace().collect();
    • let max_len = words.iter().map(|word| word.len()).max()?;
    • let longest_words: Vec<&str> = words.into_iter().filter(|&word| word.len() == max_len).collect();
    • if longest_words.len() > 1 {
    • None
    • } else {
    • longest_words.get(0).copied()
    • }
    • }