2452. 距离字典两次编辑以内的单词

This commit is contained in:
li_chx 2026-04-22 08:46:21 +08:00
parent 11a7d6775d
commit 6074be16ce
Signed by: li_chx
GPG Key ID: C7CF27EFA1E58BAC
1 changed files with 25 additions and 47 deletions

View File

@ -1,57 +1,32 @@
use crate::arr::make_matrix; use crate::arr::make_string_arr;
use std::collections::{HashMap, HashSet, VecDeque};
mod arr; mod arr;
struct Solution {} struct Solution {}
impl Solution { impl Solution {
pub fn minimum_hamming_distance( fn diff_count_less_two(a: &str, b: &str) -> bool {
source: Vec<i32>, let a = a.as_bytes();
target: Vec<i32>, let b = b.as_bytes();
allowed_swaps: Vec<Vec<i32>>, let mut cnt = 0;
) -> i32 { for i in 0..a.len() {
let mut map = HashMap::<i32, HashSet<i32>>::new(); if a[i] != b[i] {
let mut index = vec![0; target.len()]; cnt += 1;
for swp in &allowed_swaps { if cnt > 2 {
let (a, b) = (swp[0], swp[1]); return false;
map.entry(a).or_insert_with(HashSet::new).insert(b);
map.entry(b).or_insert_with(HashSet::new).insert(a);
}
let mut ans = 0;
let get_all_ele = |st : &HashSet<i32>| -> HashSet<i32> {
let mut visited = HashSet::<i32>::new();
let mut stack = st.iter().copied().collect::<VecDeque<i32>>();
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);
} }
} }
} }
visited true
};
for i in 0..source.len() {
if index[i] == -1 {
continue;
} }
if map.contains_key(&(i as i32)) { pub fn two_edit_words(queries: Vec<String>, dictionary: Vec<String>) -> Vec<String> {
let mut src_map = HashMap::<i32, i32>::new(); let mut ans = vec![];
let mut target_map = HashMap::<i32, i32>::new(); for query in queries {
for t in get_all_ele(map.get(&(i as i32)).unwrap()) { for dict in dictionary.iter() {
*src_map.entry(source[t as usize]).or_insert(0) += 1; if Self::diff_count_less_two(&query, dict) {
*target_map.entry(target[t as usize]).or_insert(0) += 1; ans.push(query.clone());
index[t as usize] = -1; break;
} }
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 ans
} }
@ -60,6 +35,9 @@ impl Solution {
fn main() { fn main() {
println!( 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"]"#)
)
); );
} }