LeetCode Week15: Word Ladder I

这周完成的题目是与BFS相关的两道题目: Word Ladder 和Word Ladder II,但是因为word LadderII那道题卡住了(至今还是RE )TT,所以这周的题解先分析Word Ladder I。

题目描述

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,

Given:

beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”, return its length 5.

Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.

我的分析

这个题目拿到的时候,其实最开始想到的是DFS或者BFS,因为考虑到每个单词之间的是恒定距离,所以这里使用了BFS。

对于初始单词,我们首先要找到与其差一个字母的单词,然后再去找与这个单词差一个字母的其他单词,依次迭代下去直到找到最终的目的单词。考虑到bfs的过程,这里使用queue类型的变量存放遍历过的单词。

对于beginword,变换其不同位置的字符,找到不同字符的单词,并利用find函数判断这个单词是否存在与字典中,如果存在,那么就表示beginword可以通过字典变换到这个单词,将单词加入队列中,并将这个单词从字典中删除。删除的目的是避免出现循环,比如hit-》hot-》hit。接下来以此遍历队列中的其他元素,找到其相差一个字母的单词放入队列中,直到找到最终的endword。

代码

通过上述分析,上述题目的代码可以写成如下形式:

class Solution {
    public:
    int ladderLength(string beginWord, string endWord, vector<string>& dict) {
        unordered_set<string> wordList;
        for(int i = 0; i < dict.size(); i++) wordList.insert(dict[i]);
        queue<pair<string,int> > bfs;
        if(wordList.find(beginWord) != wordList.end()) wordList.erase(beginWord);
        bfs.push(pair<string,int>(beginWord,1));
        int res = 1;
        while(!bfs.empty()){
            pair<string,int> cur = bfs.front(); bfs.pop();
            string word = cur.first;
            if(word == endWord) return cur.second;

            for(int i = 0; i < word.size();i++){
                for(char j = 'a'; j <= 'z'; j++){
                    string tmp = word;
                    if(tmp[i] == j) continue;
                    tmp[i] = j;
                    if(wordList.find(tmp) != wordList.end()){
                        wordList.erase(tmp);
                        bfs.push(pair<string,int>(tmp,cur.second+1));
                    }
                }

            }   
        }
        return 0;
    }
};

这里有一个问题,当时直接使用了vector类型的字典(wordlist),导致提交的时候一直超时,后来考虑到查询的时间复杂度,所以改用了set,程序就能顺利AC了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值