-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0383_ransom_note.rs
More file actions
53 lines (46 loc) · 1.17 KB
/
s0383_ransom_note.rs
File metadata and controls
53 lines (46 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#![allow(unused)]
pub struct Solution {}
use std::collections::HashMap;
impl Solution {
// O(n) O(1)
pub fn can_construct(ransom_note: String, magazine: String) -> bool {
if magazine.len() < ransom_note.len() {
return false;
}
let mut map = HashMap::new();
for ch in magazine.chars() {
let count = map.entry(ch).or_insert(0);
*count += 1;
}
for ch in ransom_note.chars() {
if !map.contains_key(&ch) {
return false;
}
if *map.get(&ch).unwrap() == 0 {
return false;
} else if let Some(c) = map.get_mut(&ch) {
*c -= 1;
}
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_383() {
assert_eq!(
Solution::can_construct("a".to_string(), "b".to_string()),
false
);
assert_eq!(
Solution::can_construct("aa".to_string(), "ab".to_string()),
false
);
assert_eq!(
Solution::can_construct("aa".to_string(), "aab".to_string()),
true
);
}
}