欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > [LeetCode] 127. 单词接龙

[LeetCode] 127. 单词接龙

2024/10/22 22:34:25 来源:https://blog.csdn.net/weixin_65043441/article/details/143023345  浏览:    关键词:[LeetCode] 127. 单词接龙

题目描述:

字典 wordList 中从单词 beginWord 到 endWord 的 转换序列 是一个按下述规格形成的序列 beginWord -> s1 -> s2 -> ... -> sk

  • 每一对相邻的单词只差一个字母。
  •  对于 1 <= i <= k 时,每个 si 都在 wordList 中。注意, beginWord 不需要在 wordList 中。
  • sk == endWord

给你两个单词 beginWord 和 endWord 和一个字典 wordList ,返回 从 beginWord 到 endWord 的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0 。 

示例 1:

输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
输出:5
解释:一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的长度 5。

示例 2:

输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
输出:0
解释:endWord "cog" 不在字典中,所以无法进行转换。

提示:

  • 1 <= beginWord.length <= 10
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • wordList[i].length == beginWord.length
  • beginWordendWord 和 wordList[i] 由小写英文字母组成
  • beginWord != endWord
  • wordList 中的所有字符串 互不相同

题目链接:

. - 力扣(LeetCode)

解题主要思路:

其实这题跟 "最小基因变化" 基本没区别,唯一的区别就是可变化的字母更多了。

"最小基因变化"链接:[LeetCode] 433. 最小基因变化-CSDN博客

解题代码:

class Solution {
public:int ladderLength(string beginWord, string endWord, vector<string>& wordList) {unordered_set<string> hash(wordList.begin(), wordList.end());if (!hash.count(endWord)) return 0;unordered_set<string> vis;queue<string> que;que.push(beginWord);vis.insert(beginWord);int ret = 1;while (que.size()) {++ret;int sz = que.size();while (sz--) {string front = que.front();que.pop();for (int i = 0; i < front.size(); ++i) {string tmp = front;for (char j = 'a'; j <= 'z'; ++j) {tmp[i] = j;if (hash.count(tmp) && !vis.count(tmp)) {if (tmp == endWord) return ret;que.push(tmp);vis.insert(tmp);}}}}}return 0;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com