news 2026/4/23 13:07:43

单词阶梯——最短的目标词链

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
单词阶梯——最短的目标词链

给定一个字符串数组 arr[],以及两个不同的字符串 start 和 target,分别代表两个单词。任务是找到从字符串起始到目标的最短链条长度 ,使得相邻单词中仅 有一个字符不同,且每个单词都存在于arr[]中。

注意:如果无法形成链条,则打印0。arr[] 数组中的每个单词大小为 m,且仅包含小写英语字母表。

示例:

输入:开始 = “toon”,target = “plea”,arr[] = [“poon”, “plee”, “same”, “poie”, “plea”, “plie”, “poin”]
输出:7
解释:toon → poon → poin → poie → plie →plee → plea

输入: start = “abcv”, target = “ebad”, arr[] = [“abcd”, “ebad”, “ebcd”, “xyza”]
输出: 4
解释: abcv → abcd → ebcd → ebad

[天真方法]:利用回溯探索所有可能的路径
我们使用回溯来解决这个问题,因为它允许我们系统地探索从起始词到目标词的所有可能变换序列,同时确保不会在给定路径中重复访问同一个词。在每一步中,我们尝试当前单词中所有可能的单字母变化,如果生成的单词存在于词典中且尚未被访问,则递归进行。回溯使算法在到达死胡同或完成路径时“回溯”,然后尝试其他选项。

这在存在多条路径、需要找到最短有效变换序列的问题中尤为有用。虽然这种方法不是最优化的,但对于性能不是关键问题的小型数据集来说,它在概念上简单且有效。通过探索所有有效的变换路径,它保证在所有可能序列中找到最小步数。

import java.util.*; public class GfG { // Recursive function to find the shortest transformation chain public static int minWordTransform(String start, String target, Map<String, Integer> mp) { // If start word is the same as target, no transformation is needed if (start.equals(target)) return 1; int mini = Integer.MAX_VALUE; // Mark current word as visited mp.put(start, 1); // Try changing each character of the word for (int i = 0; i < start.length(); i++) { char[] chars = start.toCharArray(); char originalChar = chars[i]; // Try all possible lowercase letters at position i for (char ch = 'a'; ch <= 'z'; ch++) { chars[i] = ch; String transformed = new String(chars); // If the new word exists in dictionary and is not visited if (mp.containsKey(transformed) && mp.get(transformed) == 0) { // Recursive call for next transformation mini = Math.min(mini, 1 + minWordTransform(transformed, target, mp)); } } // Restore original character before moving to the next position chars[i] = originalChar; } // Mark current word as unvisited (backtracking) mp.put(start, 0); return mini; } // Wrapper function to prepare the map and call recursive function public static int wordLadder(String start, String target, ArrayList<String> arr) { Map<String, Integer> mp = new HashMap<>(); // Initialize all words from the dictionary as unvisited for (String word : arr) { mp.put(word, 0); } int result = minWordTransform(start, target, mp); if(result==Integer.MAX_VALUE) result = 0; return result; } public static void main(String[] args) { ArrayList<String> arr = new ArrayList<>(Arrays.asList( "poon", "plee", "same", "poie", "plie", "poin", "plea")); String start = "toon"; String target = "plea"; System.out.println(wordLadder(start, target, arr)); } }

输出
6
时间复杂度:O(N⋅26L)),其中N是词典中的单词数,L是每个单词的长度。
空间复杂度:用于存储字典映射和递归调用栈,最坏情况下可达 N。

使用广度优先搜索
这个想法是用BFS找到起点和目标之间的最小链。为此,创建队列词来存储访问和 推入启动的词。在每个层级,逐一查看队列词中存储的所有元素,对每个元素,逐一更改其所有字符(a)为“z”,并检查新词是否在字典中。如果找到,将 新词推入队列,否则继续。每个队列层定义链条长度,一旦找到目标,返回该层的值 + 1。

import java.util.*; class GfG { static int wordLadder(String start, String target, String[] arr) { // Set to keep track of unvisited words Set<String> st = new HashSet<String>(); for(int i = 0; i < arr.length; i++) st.add(arr[i]); // Store the current chain length int res = 0; int m = start.length(); // Queue to store words to visit Queue<String> words = new LinkedList<>(); words.add(start); while (!words.isEmpty()) { int len = words.size(); res++; // Iterate through all words at the same level for (int i = 0; i < len; ++i) { String word = words.poll(); // For every character of the word for (int j = 0; j < m; ++j) { // Retain the original character // at the current position char[] wordArr = word.toCharArray(); char ch = wordArr[j]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { wordArr[j] = c; String newWord = new String(wordArr); // Skip the word if already added // or not present in set if (!st.contains(newWord)) continue; // If target word is found if (newWord.equals(target)) return res + 1; // Remove the word from set st.remove(newWord); // And push the newly generated word // which will be a part of the chain words.add(newWord); } // Restore the original character wordArr[j] = ch; } } } return 0; } public static void main(String[] args) { String[] arr = new String[]{"poon", "plee", "same", "poie", "plie", "poin", "plea"}; String start = "toon"; String target = "plea"; System.out.println(wordLadder(start, target, arr)); } }

输出
7
时间复杂度:O(26 * n * m * m) = O(n * m * m),其中n是arr[]的大小,m是每个单词的长度。
辅助空间:O(n * m)

编程资源 https://pan.quark.cn/s/7f7c83756948 更多资源 https://pan.quark.cn/s/bda57957c548
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/23 10:50:08

BiliTools AI视频总结功能:3个步骤让新手也能快速掌握B站精华内容

BiliTools AI视频总结功能&#xff1a;3个步骤让新手也能快速掌握B站精华内容 【免费下载链接】BiliTools A cross-platform bilibili toolbox. 跨平台哔哩哔哩工具箱&#xff0c;支持视频、音乐、番剧、课程下载……持续更新 项目地址: https://gitcode.com/GitHub_Trending…

作者头像 李华
网站建设 2026/4/23 10:48:11

Typst简历模板终极指南:10分钟打造专业求职简历的完整方案

Typst简历模板终极指南&#xff1a;10分钟打造专业求职简历的完整方案 【免费下载链接】brilliant-CV &#x1f4bc; another CV template for your job application, yet powered by Typst and more 项目地址: https://gitcode.com/gh_mirrors/br/brilliant-CV 还在为简…

作者头像 李华
网站建设 2026/4/18 13:19:17

Qwen-Image:AI绘图实现复杂文本精准编辑新突破

Qwen-Image&#xff1a;AI绘图实现复杂文本精准编辑新突破 【免费下载链接】Qwen-Image 我们隆重推出 Qwen-Image&#xff0c;这是通义千问系列中的图像生成基础模型&#xff0c;在复杂文本渲染和精准图像编辑方面取得重大突破。 项目地址: https://ai.gitcode.com/hf_mirror…

作者头像 李华
网站建设 2026/4/23 9:48:37

企业级AI部署趋势:Qwen3-VL多实例管理实战指南

企业级AI部署趋势&#xff1a;Qwen3-VL多实例管理实战指南 1. 引言&#xff1a;企业级多模态AI的演进需求 随着视觉-语言模型&#xff08;VLM&#xff09;在工业场景中的广泛应用&#xff0c;企业对AI系统的能力要求已从单一文本理解升级为跨模态感知、推理与执行一体化。Qwe…

作者头像 李华
网站建设 2026/4/23 4:38:03

Qwen3-VL视频动态理解能力解析:时间戳对齐部署案例

Qwen3-VL视频动态理解能力解析&#xff1a;时间戳对齐部署案例 1. 技术背景与核心价值 随着多模态大模型在视觉-语言任务中的广泛应用&#xff0c;对视频内容的细粒度动态理解需求日益增长。传统方法往往只能提供帧级或片段级的语义描述&#xff0c;难以实现事件与时间轴之间…

作者头像 李华
网站建设 2026/4/21 18:07:21

AI扫描仪进阶技巧:批量处理100+证件只需10分钟

AI扫描仪进阶技巧&#xff1a;批量处理100证件只需10分钟 你有没有遇到过这样的场景&#xff1f;一场大型活动即将开始&#xff0c;几百名参会者陆续到场&#xff0c;前台却堆满了身份证、护照、工作证&#xff0c;工作人员手忙脚乱地一张张拍照、录入信息&#xff0c;效率低还…

作者头像 李华