leetcode-127:单词接龙

简介: 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" 不在字典中,所以无法进行转换。

解题

参考链接

方法一:bfs

这里无向图求最短路,广搜最为合适,广搜只要搜到了终点,那么一定是最短的路径

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> wordSet(wordList.begin(),wordList.end());
        if(wordSet.count(endWord)==0) return 0;
        unordered_map<string,int> mp;  //<word, 查询到这个word路径长度>
        queue<string> q;
        q.push(beginWord);
        mp[beginWord]=1;
        while(!q.empty()){
            string cur=q.front();
            q.pop();
            int path=mp[cur];
            for(int i=0;i<cur.size();i++){
                string next=cur;
                for(int j=0;j<26;j++){
                    next[i]=j+'a';
                    if(next==endWord) return path+1;
                    if(wordSet.count(next)&&mp.count(next)==0){// wordSet出现了next,并且next没有被访问过
                        mp[next]=path+1;
                        q.push(next);
                    }
                }
            }
        }
        return 0;
    }
};

由于复杂度的原因,如果采用遍历wordList,在判断是否就一个字母换掉,那么500010次执行
这里采用枚举的方法,最多遍历 10
26次。

相关文章
|
5天前
leetcode127单词接龙刷题打卡
leetcode127单词接龙刷题打卡
17 0
|
10月前
|
算法 Java C++
leetcode单词接龙
leetcode单词接龙
☆打卡算法☆LeetCode 127. 单词接龙 算法解析
“给定两个单词beginWord和endWord,以及一个字典wordList,找出并返回所有从beginWord到endWrod之间的最短转换序列中的单词数目。”
☆打卡算法☆LeetCode 126. 单词接龙 II 算法解析
“给定两个单词beginWord和endWord,以及一个字典wordList,找出并返回所有从beginWord到endWrod之间的最短转换序列。”
|
算法
​LeetCode刷题实战126:单词接龙 II
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
195 0
[leetcode/lintcode 题解] 阿里算法面试题:单词接龙 II
[leetcode/lintcode 题解] 阿里算法面试题:单词接龙 II
[leetcode/lintcode 题解] 阿里算法面试题:单词接龙 II
|
5天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
5天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
12 0