-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0242_valid_anagram.rs
More file actions
45 lines (39 loc) · 1006 Bytes
/
s0242_valid_anagram.rs
File metadata and controls
45 lines (39 loc) · 1006 Bytes
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
#![allow(unused)]
pub struct Solution {}
use std::collections::HashMap;
impl Solution {
// O(N) O(N) N is the length of s;
pub fn is_anagram(s: String, t: String) -> bool {
if s.len() != t.len() {
return false;
}
let mut map = HashMap::new();
for ch in s.chars() {
let count = map.entry(ch).or_insert(0);
*count += 1;
}
for ch in t.chars() {
if !map.contains_key(&ch) || *map.get(&ch).unwrap() == 0 {
return false;
} else if let Some(count) = map.get_mut(&ch) {
*count -= 1;
}
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_242() {
assert_eq!(
Solution::is_anagram("anagram".to_string(), "nagaram".to_string(),),
true
);
assert_eq!(
Solution::is_anagram("rat".to_string(), "car".to_string(),),
false
);
}
}