383. 赎金信

题目描述

给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。

如果可以,返回 true ;否则返回 false 。

magazine 中的每个字符只能在 ransomNote 中使用一次。

解题思路

#![allow(unused)]

fn main() {
struct Solution {}

impl Solution {
    pub fn can_construct(ransom_note: String, magazine: String) -> bool {
        use std::collections::HashMap;
        let mut map: HashMap<char, usize> = HashMap::new();
        for c in magazine.chars() {
            *map.entry(c).or_default() += 1;
        }
        for c in ransom_note.chars() {
            if ! map.contains_key(&c) { return false }
            let a = map.get_mut(&c).unwrap();
            *a -= 1;
            if *a == 0 { map.remove(&c); }
        }
        true
    }
}
}

学习感想

普通hashmap 的使用