Rust 的 entry API 提供了一個檢視,讓你能查看映射中的單一項目。映射可以是HashMap或BTreeMap。
這個項目可能處於已佔用或空置狀態,而 API 提供了方法來修改項目的內容。
在這項練習中,你會使用HashMap以及 entry API 的方法,來解決一個簡單的演算法問題。
給定&[&str],代表一篇雜誌文章的詞語,以及&[&str],代表你想寄出的便條的詞語,你能從雜誌中剪下詞語、貼到信件上,拼湊出你的便條嗎?
注意事項:
你會從以下這個待實作的函式簽章開始:
pub fn can_construct_note(magazine: &[&str], note: &[&str]) -> bool {
todo!()
}
給定以下輸入
let magazine = "two times three is not four".split_whitespace().collect::<Vec<&str>>();
let note = "two times two is four".split_whitespace().collect::<Vec<&str>>();
assert!(!can_construct_note(&magazine, ¬e));
這個函式會回傳false,因為雜誌裡只有一個"two",而便條需要兩個。
以下輸入則會成功:
let magazine = "Astronomer Amy Mainzer spent hours chatting with Leonardo DiCaprio for Netflix's 'Don't Look Up'".split_whitespace().collect::<Vec<&str>>();
let note = "Amy Mainzer chatting with Leonardo DiCaprio"
.split_whitespace()
.collect::<Vec<&str>>();
assert!(can_construct_note(&magazine, ¬e));
這個函式會回傳true,因為雜誌含有便條所需的所有詞語。