This commit is contained in:
2025-06-20 11:27:53 +08:00
parent 3b805a6422
commit 003eb24c77
6 changed files with 238 additions and 1 deletions

View File

@@ -0,0 +1,6 @@
[package]
name = "p383"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@@ -0,0 +1,44 @@
struct Solution;
impl Solution {
pub fn can_construct(ransom_note: String, magazine: String) -> bool {
// 提前判断
if ransom_note.len() > magazine.len() {
return false;
}
let mut char_counts = [0; 128];
// 统计magazine中每个字符的出现次数
for &b in magazine.as_bytes() {
char_counts[b as usize] += 1;
}
// 减去ransom_note中的字符
for &b in ransom_note.as_bytes() {
char_counts[b as usize] -= 1;
if char_counts[b as usize] < 0 {
return false;
}
}
true
}
}
fn main() {
let test_cases = [
("a", "b", false),
("aa", "ab", false),
("aa", "aab", true),
("", "", true),
];
for (note, mag, expected) in test_cases {
let result = Solution::can_construct(note.to_string(), mag.to_string());
println!(
"Can \"{}\" be constructed from \"{}\"? {} (Expected: {})",
note, mag, result, expected
);
}
}