From 6074be16ce4d714c73acc2aa09e1088aaeef9472 Mon Sep 17 00:00:00 2001 From: li_chx Date: Wed, 22 Apr 2026 08:46:21 +0800 Subject: [PATCH] =?UTF-8?q?2452.=20=E8=B7=9D=E7=A6=BB=E5=AD=97=E5=85=B8?= =?UTF-8?q?=E4=B8=A4=E6=AC=A1=E7=BC=96=E8=BE=91=E4=BB=A5=E5=86=85=E7=9A=84?= =?UTF-8?q?=E5=8D=95=E8=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 72 +++++++++++++++++++---------------------------------- 1 file changed, 25 insertions(+), 47 deletions(-) diff --git a/src/main.rs b/src/main.rs index f845ca4..8e117ee 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,57 +1,32 @@ -use crate::arr::make_matrix; - -use std::collections::{HashMap, HashSet, VecDeque}; +use crate::arr::make_string_arr; mod arr; struct Solution {} impl Solution { - pub fn minimum_hamming_distance( - source: Vec, - target: Vec, - allowed_swaps: Vec>, - ) -> i32 { - let mut map = HashMap::>::new(); - let mut index = vec![0; target.len()]; - for swp in &allowed_swaps { - let (a, b) = (swp[0], swp[1]); - map.entry(a).or_insert_with(HashSet::new).insert(b); - map.entry(b).or_insert_with(HashSet::new).insert(a); + fn diff_count_less_two(a: &str, b: &str) -> bool { + let a = a.as_bytes(); + let b = b.as_bytes(); + let mut cnt = 0; + for i in 0..a.len() { + if a[i] != b[i] { + cnt += 1; + if cnt > 2 { + return false; + } + } } - let mut ans = 0; - let get_all_ele = |st : &HashSet| -> HashSet { - let mut visited = HashSet::::new(); - let mut stack = st.iter().copied().collect::>(); - while let Some(cur) = stack.pop_front() { - visited.insert(cur); - for &nxt in map.get(&cur).unwrap_or(&HashSet::new()) { - if !visited.contains(&nxt) { - stack.push_back(nxt); - } + true + } + pub fn two_edit_words(queries: Vec, dictionary: Vec) -> Vec { + let mut ans = vec![]; + for query in queries { + for dict in dictionary.iter() { + if Self::diff_count_less_two(&query, dict) { + ans.push(query.clone()); + break; } } - visited - }; - for i in 0..source.len() { - if index[i] == -1 { - continue; - } - if map.contains_key(&(i as i32)) { - let mut src_map = HashMap::::new(); - let mut target_map = HashMap::::new(); - for t in get_all_ele(map.get(&(i as i32)).unwrap()) { - *src_map.entry(source[t as usize]).or_insert(0) += 1; - *target_map.entry(target[t as usize]).or_insert(0) += 1; - index[t as usize] = -1; - } - let mut local_ans = 0; - for (k, v) in target_map { - local_ans += (v - *src_map.get(&k).unwrap_or(&0)).max(0); - } - ans += local_ans; - continue; - } - ans += if source[i] == target[i] { 0 } else { 1 }; } ans } @@ -60,6 +35,9 @@ impl Solution { fn main() { println!( "{:?}", - Solution::minimum_hamming_distance(vec![18,42,18,64], vec![61,94,18,44], make_matrix("[[2,3],[0,1],[3,1]]")) + Solution::two_edit_words( + make_string_arr(r#"["word","note","ants","wood"]"#), + make_string_arr(r#"["wood","joke","moat"]"#) + ) ); }