-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_anagram.rs
78 lines (67 loc) · 1.87 KB
/
valid_anagram.rs
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use std::collections::HashMap;
/// Given two strings `s` and `t`, return `true` if `t` is an
/// anagram of `s`, and `false` otherwise.
///
/// An anagram is a word or phrase formed by rearranging the letters of a
/// different word or phrase, typically using all the original letters exactly
/// once.
struct Solution;
impl Solution {
fn add_letters(s: String) -> HashMap<char, i32> {
let mut letters = HashMap::new();
for c in s.chars() {
letters
.entry(c)
.and_modify(|c| {
*c += 1;
})
.or_insert(1);
}
letters
}
fn remove_letters(letters: &mut HashMap<char, i32>, t: String) -> bool {
let mut result = true;
for c in t.chars() {
let value = letters.get(&c);
if value.is_none() {
result = false;
break;
} else {
let mut count = *value.unwrap();
count -= 1;
if count == 0 {
letters.remove(&c);
} else {
letters.insert(c, count);
}
}
}
if result {
result = letters.len() == 0;
}
result
}
pub fn is_anagram(s: String, t: String) -> bool {
let mut letters = Self::add_letters(s);
let result = Self::remove_letters(&mut letters, t);
result
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let s = "anagram".to_string();
let t = "nagaram".to_string();
let result = Solution::is_anagram(s, t);
assert!(result);
}
#[test]
fn example_2() {
let s = "rat".to_string();
let t = "car".to_string();
let result = Solution::is_anagram(s, t);
assert!(!result);
}
}