use std::collections::HashMap;
fn main() {
let text = "banana";
let mut freq = HashMap::new();
for ch in text.chars() {
let count = freq.entry(ch).or_insert(0);
*count += 1;
}
println!("{:?}", freq);
}The code counts each character's occurrences in the string "banana". 'b' appears once, 'a' appears three times, and 'n' appears twice. The printed HashMap shows these counts.
Anagrams have the same characters with the same frequency. Using a frequency counter helps count characters in both strings and compare these counts to confirm if they are anagrams.
use std::collections::HashMap;
fn main() {
let text = "apple";
let mut freq = HashMap::new();
for ch in text.chars() {
freq.insert(ch, freq[&ch] + 1);
}
println!("{:?}", freq);
}The code tries to access freq[&ch] before the key exists in the HashMap, causing a panic at runtime because the key is missing.
use std::collections::HashMap;
fn main() {
let words = vec!["cat", "dog", "cat", "bird", "dog", "dog"];
let mut freq = HashMap::new();
for word in words {
let count = freq.entry(word).or_insert(0);
*count += 1;
}
println!("{:?}", freq);
}The vector contains "cat" twice, "dog" three times, and "bird" once. The HashMap stores these counts.
Option C uses one HashMap to count frequencies from the first array and subtract frequencies from the second. If all counts return to zero, arrays have the same frequency of elements.
