|
1 |
| -// pub struct Solution {} |
2 |
| -// impl Solution { |
| 1 | +use std::collections::HashSet; |
| 2 | + |
| 3 | +// Time: O(n) |
| 4 | +// Space: O(1) |
| 5 | + |
| 6 | +// pub struct Solution1 {} |
| 7 | +// impl Solution1 { |
| 8 | +// pub fn find_the_difference(s: String, t: String) -> char { |
| 9 | +// 'e' |
| 10 | +// } |
| 11 | +// } |
| 12 | + |
| 13 | +// pub struct Solution2 {} |
| 14 | +// impl Solution2 { |
| 15 | +// pub fn find_the_difference(s: String, t: String) -> char { |
| 16 | +// 'e' |
| 17 | +// } |
| 18 | +// } |
| 19 | + |
| 20 | +// https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/find-the-difference.py#L18 |
| 21 | +pub struct Solution3 {} |
| 22 | +impl Solution3 { |
| 23 | + pub fn find_the_difference(s: String, t: String) -> char { |
| 24 | + let s_chars: HashSet<char> = s.chars().collect(); |
| 25 | + let mut t_chars: HashSet<char> = t.chars().collect(); |
| 26 | + s_chars.iter().for_each(|c| { |
| 27 | + t_chars.remove(c); |
| 28 | + }); |
| 29 | + t_chars.into_iter().collect::<Vec<char>>()[0] |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// pub struct Solution4 {} |
| 34 | +// impl Solution4 { |
| 35 | +// pub fn find_the_difference(s: String, t: String) -> char { |
| 36 | +// 'e' |
| 37 | +// } |
| 38 | +// } |
| 39 | + |
| 40 | +// https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/find-the-difference.py#L33 |
| 41 | +pub struct Solution5 {} |
| 42 | +impl Solution5 { |
| 43 | + pub fn find_the_difference(s: String, t: String) -> char { |
| 44 | + let s_chars: HashSet<char> = s.chars().collect(); |
| 45 | + let t_chars: HashSet<char> = t.chars().collect(); |
| 46 | + // or https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.symmetric_difference |
| 47 | + let diff: HashSet<&char> = t_chars.difference(&s_chars).collect(); |
| 48 | + *(diff.into_iter().collect::<Vec<&char>>()[0]) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// pub struct Solution6 {} |
| 53 | +// impl Solution6 { |
3 | 54 | // pub fn find_the_difference(s: String, t: String) -> char {
|
4 | 55 | // 'e'
|
5 | 56 | // }
|
6 | 57 | // }
|
7 | 58 |
|
8 | 59 | #[cfg(test)]
|
9 | 60 | mod tests {
|
10 |
| - // Note this useful idiom: importing names from outer (for mod tests) scope. |
11 | 61 | use super::*;
|
12 | 62 |
|
13 | 63 | #[test]
|
14 | 64 | fn test_find_the_difference() {
|
15 |
| - // assert_eq!(Solution::find_the_difference("abcd".to_string(), "abcde".to_string()), 'e'); |
| 65 | + assert_eq!( |
| 66 | + Solution3::find_the_difference("abcd".to_string(), "abcde".to_string()), |
| 67 | + 'e' |
| 68 | + ); |
| 69 | + assert_eq!( |
| 70 | + Solution5::find_the_difference("abcd".to_string(), "abcde".to_string()), |
| 71 | + 'e' |
| 72 | + ); |
16 | 73 | }
|
17 | 74 | }
|
0 commit comments