update
This commit is contained in:
6
leetcode_rs/problems/p383/Cargo.toml
Normal file
6
leetcode_rs/problems/p383/Cargo.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "p383"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
44
leetcode_rs/problems/p383/src/main.rs
Normal file
44
leetcode_rs/problems/p383/src/main.rs
Normal 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
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user