Complete the code to check if two strings have the same length.
fn are_anagrams(s1: &str, s2: &str) -> bool {
if s1.len() [1] s2.len() {
return false;
}
true
}We return false if the lengths are not equal, so the condition should check for inequality.
Complete the code to sort the characters of a string.
fn sorted_chars(s: &str) -> Vec<char> {
let mut chars: Vec<char> = s.chars().collect();
chars.[1]();
chars
}We use the 'sort' method to arrange characters in ascending order.
Fix the error in comparing sorted character vectors for anagram check.
fn are_anagrams(s1: &str, s2: &str) -> bool {
let mut v1: Vec<char> = s1.chars().collect();
let mut v2: Vec<char> = s2.chars().collect();
v1.sort();
v2.sort();
v1 [1] v2
}To check if two strings are anagrams, their sorted character vectors must be equal.
Fill both blanks to count character frequencies using a HashMap.
use std::collections::HashMap;
fn char_count(s: &str) -> HashMap<char, usize> {
let mut map = HashMap::new();
for c in s.chars() {
*map.entry(c).[1](0) += 1;
}
map
}
fn are_anagrams(s1: &str, s2: &str) -> bool {
char_count(s1) [2] char_count(s2)
}Use 'or_insert(0)' to initialize count, and '==' to compare frequency maps.
Fill all three blanks to implement an anagram check using character counts.
use std::collections::HashMap;
fn are_anagrams(s1: &str, s2: &str) -> bool {
if s1.len() != s2.len() {
return false;
}
let mut count = HashMap::new();
for c in s1.chars() {
*count.entry(c).[1](0) += 1;
}
for c in s2.chars() {
let counter = count.entry(c).[2](0);
if *counter == 0 {
return false;
}
*counter -= [3];
}
true
}Use 'or_insert(0)' to initialize counts and subtract 1 for each character in s2.
