Rust 的条目 API 提供了对映射中单个条目的视图,这个映射既可以是HashMap,也可以是BTreeMap。
条目可能已被占用,也可能处于空闲状态,API 还提供了修改条目内容的方法。
在这个练习中,你将使用 HashMap 以及入口 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,因为杂志包含了便条所需的全部单词。