news 2026/4/18 23:15:24

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

作者头像

张小明

前端开发工程师

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/18 12:28:23

看完就想试!Qwen-Image-2512-ComfyUI生成非遗海报

看完就想试&#xff01;Qwen-Image-2512-ComfyUI生成非遗海报 1. 引言&#xff1a;AI赋能非遗文化表达的新方式 在数字内容创作日益普及的今天&#xff0c;如何高效、精准地呈现具有深厚文化底蕴的设计作品&#xff0c;成为设计师和文化传播者面临的重要课题。阿里开源的 Qwe…

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

32B大模型零成本上手:Granite-4.0微调全攻略

32B大模型零成本上手&#xff1a;Granite-4.0微调全攻略 【免费下载链接】granite-4.0-h-small-unsloth-bnb-4bit 项目地址: https://ai.gitcode.com/hf_mirrors/unsloth/granite-4.0-h-small-unsloth-bnb-4bit IBM最新发布的320亿参数大语言模型Granite-4.0-H-Small&a…

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

索尼Xperia刷机革命:3大秘籍让你的旧设备性能翻倍重生

索尼Xperia刷机革命&#xff1a;3大秘籍让你的旧设备性能翻倍重生 【免费下载链接】Flashtool Xperia device flashing 项目地址: https://gitcode.com/gh_mirrors/fl/Flashtool 还在为索尼Xperia设备卡顿、电池续航差、系统臃肿而苦恼吗&#xff1f;你是否想过&#xf…

作者头像 李华
网站建设 2026/4/18 14:44:26

AI也能谱交响乐?NotaGen大模型镜像使用全攻略

AI也能谱交响乐&#xff1f;NotaGen大模型镜像使用全攻略 在一次音乐创作工作坊中&#xff0c;一位作曲系学生尝试用AI辅助完成毕业作品。他原本计划花数周构思主题与和声结构&#xff0c;直到发现一个名为 NotaGen 的本地化音乐生成系统——通过选择“浪漫主义时期 肖邦 键…

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

AI视频摘要工具:智能内容管理新革命

AI视频摘要工具&#xff1a;智能内容管理新革命 【免费下载链接】BiliTools A cross-platform bilibili toolbox. 跨平台哔哩哔哩工具箱&#xff0c;支持视频、音乐、番剧、课程下载……持续更新 项目地址: https://gitcode.com/GitHub_Trending/bilit/BiliTools 你是否…

作者头像 李华
网站建设 2026/4/17 7:50:37

BongoCat桌面萌宠终极指南:让枯燥的电脑操作充满惊喜与乐趣

BongoCat桌面萌宠终极指南&#xff1a;让枯燥的电脑操作充满惊喜与乐趣 【免费下载链接】BongoCat 让呆萌可爱的 Bongo Cat 陪伴你的键盘敲击与鼠标操作&#xff0c;每一次输入都充满趣味与活力&#xff01; 项目地址: https://gitcode.com/gh_mirrors/bong/BongoCat 你…

作者头像 李华