news 2026/9/3 0:41:50

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

作者头像

张小明

前端开发工程师

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/8/30 10:19:19

Kimi-Audio开源:70亿参数全能音频AI模型终极指南

Kimi-Audio开源&#xff1a;70亿参数全能音频AI模型终极指南 【免费下载链接】Kimi-Audio-7B-Instruct 我们推出 Kimi-Audio——一个在音频理解、生成与对话方面表现卓越的开源音频基础模型。本仓库提供 Kimi-Audio-7B-Instruct 的模型检查点。 项目地址: https://ai.gitcode…

作者头像 李华
网站建设 2026/9/2 0:20:55

iOS应用自由安装:AppSync Unified使用全攻略

iOS应用自由安装&#xff1a;AppSync Unified使用全攻略 【免费下载链接】AppSync Unified AppSync dynamic library for iOS 5 and above. 项目地址: https://gitcode.com/gh_mirrors/ap/AppSync 想要在越狱设备上自由安装各种应用吗&#xff1f;AppSync Unified正是你…

作者头像 李华
网站建设 2026/8/30 18:18:51

QRemeshify终极指南:从零基础到网格优化大师的完整解析

QRemeshify终极指南&#xff1a;从零基础到网格优化大师的完整解析 【免费下载链接】QRemeshify A Blender extension for an easy-to-use remesher that outputs good-quality quad topology 项目地址: https://gitcode.com/gh_mirrors/qr/QRemeshify 在3D建模的世界中…

作者头像 李华
网站建设 2026/9/2 9:38:13

自动驾驶感知测试:YOLOE镜像识别多类别物体

自动驾驶感知测试&#xff1a;YOLOE镜像识别多类别物体 在自动驾驶系统的感知模块中&#xff0c;实时、准确地识别道路上的各类物体是确保安全行驶的核心能力。传统目标检测模型通常受限于预定义类别&#xff0c;难以应对开放世界中的未知物体。而YOLOE&#xff08;You Only L…

作者头像 李华
网站建设 2026/9/2 1:50:05

构建智能知识库第一步:MinerU文档向量化预处理

构建智能知识库第一步&#xff1a;MinerU文档向量化预处理 1. 引言&#xff1a;为什么需要智能文档理解&#xff1f; 在构建企业级或研究型智能知识库的过程中&#xff0c;原始文档的结构化处理是至关重要的第一步。传统OCR技术虽然能够提取文本内容&#xff0c;但在面对复杂…

作者头像 李华
网站建设 2026/9/2 18:47:54

Stable Diffusion XL vs 麦橘超然实测:云端2小时低成本对比

Stable Diffusion XL vs 麦橘超然实测&#xff1a;云端2小时低成本对比 对于摄影工作室来说&#xff0c;时间就是金钱。当客户项目迫在眉睫&#xff0c;而专业显卡采购流程却需要一个月的审批周期时&#xff0c;如何快速决策引入AI修图方案就成了生死攸关的问题。本文将带你用…

作者头像 李华