From 52d2e3e7a42e62a5233577f36235a0c9e93d696e Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 14 Jan 2024 16:33:38 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=E2=80=9C1657.=20Determine=20if=20T?= =?UTF-8?q?wo=20Strings=20Are=20Close=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/determine-if-two-strings-are-close.rs | 39 ++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 rs/determine-if-two-strings-are-close.rs diff --git a/rs/determine-if-two-strings-are-close.rs b/rs/determine-if-two-strings-are-close.rs new file mode 100644 index 0000000..e1c9c99 --- /dev/null +++ b/rs/determine-if-two-strings-are-close.rs @@ -0,0 +1,39 @@ +use std::convert::TryFrom; + +impl Solution { + fn freqs(word: &str) -> Vec { + let mut f = vec![0; 26]; + + let zero = u8::try_from('a').unwrap(); + for c in word.chars().filter_map(|c| match u8::try_from(c) { + Ok(val) => Some(val), + _ => None, + }) { + f[(c - zero) as usize] += 1; + } + + f + } + + fn mask(f: &[usize]) -> i32 { + let mut m = 0; + + for c in f { + m = (m << 1) | if *c > 0 { 1 } else { 0 }; + } + + m + } + + pub fn close_strings(word1: String, word2: String) -> bool { + let mut f1 = Solution::freqs(&word1); + let m1 = Solution::mask(&f1); + f1.sort(); + + let mut f2 = Solution::freqs(&word2); + let m2 = Solution::mask(&f2); + f2.sort(); + + m1 == m2 && f1 == f2 + } +}