-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_the_difference.rs
74 lines (65 loc) · 1.97 KB
/
find_the_difference.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
use std::collections::HashSet;
// Time: O(n)
// Space: O(1)
// pub struct Solution1 {}
// impl Solution1 {
// pub fn find_the_difference(s: String, t: String) -> char {
// 'e'
// }
// }
// pub struct Solution2 {}
// impl Solution2 {
// pub fn find_the_difference(s: String, t: String) -> char {
// 'e'
// }
// }
// https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/find-the-difference.py#L18
pub struct Solution3 {}
impl Solution3 {
pub fn find_the_difference(s: String, t: String) -> char {
let s_chars: HashSet<char> = s.chars().collect();
let mut t_chars: HashSet<char> = t.chars().collect();
s_chars.iter().for_each(|c| {
t_chars.remove(c);
});
t_chars.into_iter().collect::<Vec<char>>()[0]
}
}
// pub struct Solution4 {}
// impl Solution4 {
// pub fn find_the_difference(s: String, t: String) -> char {
// 'e'
// }
// }
// https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/find-the-difference.py#L33
pub struct Solution5 {}
impl Solution5 {
pub fn find_the_difference(s: String, t: String) -> char {
let s_chars: HashSet<char> = s.chars().collect();
let t_chars: HashSet<char> = t.chars().collect();
// or https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.symmetric_difference
let diff: HashSet<&char> = t_chars.difference(&s_chars).collect();
*(diff.into_iter().collect::<Vec<&char>>()[0])
}
}
// pub struct Solution6 {}
// impl Solution6 {
// pub fn find_the_difference(s: String, t: String) -> char {
// 'e'
// }
// }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_the_difference() {
assert_eq!(
Solution3::find_the_difference("abcd".to_string(), "abcde".to_string()),
'e'
);
assert_eq!(
Solution5::find_the_difference("abcd".to_string(), "abcde".to_string()),
'e'
);
}
}