How to check whether the letters of a word exist in a string (order doesn't matter) in Rust

1 Answer

0 votes
/// Determines whether all letters in `word` can be formed
/// from the letters available in `sentence`.
///
/// Rules:
/// - Letter order does not matter.
/// - Comparison is case-insensitive.
/// - Non-alphabetic characters are ignored.
///
/// # Arguments
///
/// * `sentence` - Source text containing available letters.
/// * `word` - Word to check.
///
/// # Returns
///
/// `true` if the word can be formed; otherwise `false`.
fn contains_word_letters(sentence: &str, word: &str) -> bool {
    let mut available = [0_u32; 26];

    // Count available letters in the sentence.
    for ch in sentence.chars() {
        let ch = ch.to_ascii_lowercase();

        if ch.is_ascii_lowercase() {
            available[(ch as u8 - b'a') as usize] += 1;
        }
    }

    // Consume letters required by the word.
    for ch in word.chars() {
        let ch = ch.to_ascii_lowercase();

        if !ch.is_ascii_lowercase() {
            continue;
        }

        let index = (ch as u8 - b'a') as usize;

        if available[index] == 0 {
            return false;
        }

        available[index] -= 1;
    }

    true
}

fn main() {
    let sentence = "Bright stars shine above calm valleys at night.";

    println!(
        "{}",
        contains_word_letters(sentence, "satellite")
    );

    println!(
        "{}",
        contains_word_letters(sentence, "satellllite")
    );
}



/*
run:

true
false

*/

 



answered Sep 27 by avibootz

Related questions

...