mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
rs: add “1657. Determine if Two Strings Are Close”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
a1de882ad5
commit
52d2e3e7a4
1 changed files with 39 additions and 0 deletions
39
rs/determine-if-two-strings-are-close.rs
Normal file
39
rs/determine-if-two-strings-are-close.rs
Normal file
|
@ -0,0 +1,39 @@
|
|||
use std::convert::TryFrom;
|
||||
|
||||
impl Solution {
|
||||
fn freqs(word: &str) -> Vec<usize> {
|
||||
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
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue