How to check if a string can be constructed by using the letters of another string in Rust

1 Answer

0 votes
fn can_construct(s: &str, another: &str) -> bool {
    let mut freq = [0i32; 256]; // ASCII frequency table

    // Count characters in `another`
    for &byte in another.as_bytes() {
        freq[byte as usize] += 1;
    }

    // Check if `s` can be constructed
    for &byte in s.as_bytes() {
        let idx = byte as usize;
        freq[idx] -= 1;
        if freq[idx] < 0 {
            return false;
        }
    }

    true
}

fn main() {
    let s = "hello";
    let another = "olehhlxyz";

    println!("{}", can_construct(s, another));
}




/*
run:

true

*/

 



answered Jan 5 by avibootz

Related questions

...