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 std::collections::{HashMap, HashSet, VecDeque};
use crate::arr::make_string_arr;
mod arr;
struct Solution {}
impl Solution {
pub fn minimum_hamming_distance(
source: Vec<i32>,
target: Vec<i32>,
allowed_swaps: Vec<Vec<i32>>,
) -> i32 {
let mut map = HashMap::<i32, HashSet<i32>>::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<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);
}
true
}
pub fn two_edit_words(queries: Vec<String>, dictionary: Vec<String>) -> Vec<String> {
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::<i32, i32>::new();
let mut target_map = HashMap::<i32, i32>::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"]"#)
)
);
}