Skip to content

Commit

Permalink
leetcode: Add 0383
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed May 11, 2024
1 parent b9984f9 commit 2261238
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/leetcode/0383.ransom-note/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0383-ransom-note"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
4 changes: 4 additions & 0 deletions src/leetcode/0383.ransom-note/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

#

[问题描述](../problems/)
57 changes: 57 additions & 0 deletions src/leetcode/0383.ransom-note/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use std::collections::HashMap;

// HashTable
// 字典计数
pub fn can_construct1(ransom_note: String, magazine: String) -> bool {
debug_assert!(!ransom_note.is_empty());
debug_assert!(!magazine.is_empty());

// 统计字符数.
let mut map: HashMap<char, usize> = HashMap::with_capacity(magazine.len());
for chr in magazine.chars() {
*map.entry(chr).or_default() += 1;
}

// 遍历 ransom_note, 并把相应的字符从字典中减去.
for chr in ransom_note.chars() {
match map.get_mut(&chr) {
Some(count) if *count > 0 => *count -= 1,
_ => return false,
}
}
true
}

pub type SolutionFn = fn(String, String) -> bool;

fn check_solution(func: SolutionFn) {
let ransom_note = "a".to_owned();
let magazine = "b".to_owned();
assert!(!func(ransom_note, magazine));

let ransom_note = "aa".to_owned();
let magazine = "ab".to_owned();
assert!(!func(ransom_note, magazine));

let ransom_note = "aa".to_owned();
let magazine = "aab".to_owned();
assert!(func(ransom_note, magazine));
}

fn main() {
check_solution(can_construct1);
}

#[cfg(test)]
mod tests {
use super::{can_construct1, check_solution};

#[test]
fn test_can_construct1() {
check_solution(can_construct1);
}
}

0 comments on commit 2261238

Please sign in to comment.