leetcode127.单词接龙

 本题的思路就是将所有可转换的序列相连,构成图,然后选择起始词作为广度优先遍历的起点,那么就能找到转换的最小步骤数

而这里的两个单词是否相连不是真的把他们弄成一张图,而是采用暴力枚举,逐个尝试替换字母,然后判断替换后的单词是否在原来的字典中,如果在,那么二者就是相连的

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        //将单词列表转化为哈希表
        unordered_set<string> wordSet(wordList.begin(),wordList.end());
        //用来判断单词是否已经访问过,并且记录转换到当前单词需要的步数
        unordered_map<string,int> visitedMap;

        queue<string> que;
        que.push(beginWord);
        visitedMap.insert(pair<string,int>(beginWord,1));
        while(!que.empty()){
            string currentWord=que.front();
            que.pop();
            int step=visitedMap[currentWord];
            for(int i=0;i<currentWord.size();i++){
                string newWord=currentWord;
                for(int j=0;j<26;j++){
                    newWord[i]='a'+j;
                    //找到结果单词且结果单词在字典中直接把步骤数目返回
                    if(endWord==newWord&&wordSet.find(newWord)!=wordSet.end())
                        return step+1;
                    //如果替换得到的单词存在于字典中并且从来没有访问过
                    else if(wordSet.find(newWord)!=wordSet.end()&&visitedMap.find(newWord)==visitedMap.end()){
                        que.push(newWord);
                        visitedMap.insert(pair<string,int>(newWord,step+1));
                    }
                }
            }
        }
        //不能转换到endWord,返回0
        return 0;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值