From 84ceb51cb16270f7d59dc79e17e8b64ce42e8eeb Mon Sep 17 00:00:00 2001 From: Bauke Date: Fri, 8 Apr 2022 14:59:10 +0200 Subject: [PATCH] Solve valid-anagram. --- source/lib.rs | 1 + source/valid_anagram/mod.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 source/valid_anagram/mod.rs diff --git a/source/lib.rs b/source/lib.rs index 51f671a..602c50e 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -7,4 +7,5 @@ pub mod plus_one; pub mod reverse_integer; pub mod roman_to_integer; pub mod two_sum; +pub mod valid_anagram; pub mod valid_parenthesis; diff --git a/source/valid_anagram/mod.rs b/source/valid_anagram/mod.rs new file mode 100644 index 0000000..2aff0d5 --- /dev/null +++ b/source/valid_anagram/mod.rs @@ -0,0 +1,31 @@ +pub fn is_anagram(a: String, b: String) -> bool { + // Both strings must have the same length otherwise they can't be anagrams. + if a.len() != b.len() { + return false; + } + + // Sort both strings' characters so they're in alphabetical order. + let mut a = a.chars().collect::>(); + a.sort(); + + let mut b = b.chars().collect::>(); + b.sort(); + + // And if they are equal, then they're anagrams. + a == b +} + +#[test] +fn test_valid_anagram() { + let samples = [ + (("💖🌠banana", "an💖anab🌠"), true), + (("anagram", "nagaram"), true), + (("bats", "tabs"), true), + (("rat", "cat"), false), + (("bats", "bat"), false), + ]; + + for ((a, b), expected) in samples { + assert_eq!(is_anagram(a.to_string(), b.to_string()), expected); + } +}