diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 642a89e..6f67282 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -124,4 +124,5 @@ mod p73_set_matrix_zeroes; mod p289_game_of_life; mod p383_ransom_note; mod p290_word_pattern; -mod p205_isomorphic_strings; \ No newline at end of file +mod p205_isomorphic_strings; +mod p242_valid_anagram; \ No newline at end of file diff --git a/src/problem/p242_valid_anagram.rs b/src/problem/p242_valid_anagram.rs new file mode 100644 index 0000000..dfa4d51 --- /dev/null +++ b/src/problem/p242_valid_anagram.rs @@ -0,0 +1,49 @@ +/** + * [242] Valid Anagram + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn is_anagram(s: String, t: String) -> bool { + let mut map = HashMap::new(); + + for c in s.chars() { + let entry = map.entry(c).or_insert(0); + + *entry += 1; + } + + for c in t.chars() { + match map.get_mut(&c) { + Some(value) => { + *value -= 1; + + if *value == 0 { + map.remove(&c); + } + }, + None => { + return false; + } + } + } + + map.len() == 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_242() { + assert!(Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned())); + } +}