127. Word Ladder

单向bfs
方法也是想到和写了出来,就是没有用find这个方法导致超时!!!用了iterator
其实就是bfs不断判断是否是那就ok了,数据结构的使用方法还是有点弱!

class Solution {
public:
    void addnext(string s, queue<string>& qu, unordered_set<string>& wordList){
        wordList.erase(s);
        for(int i = 0; i < s.length(); ++ i){
            char temp = s[i];
            for(int j = 0; j < 26; ++ j){
                s[i] = 'a' + j;
                if(wordList.find(s) != wordList.end()){
                    qu.push(s);
                    wordList.erase(s);
                }
            }
            s[i] = temp;
        }
    }
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        wordList.insert(endWord);
        queue<string>qu;
        addnext(beginWord, qu, wordList);
        int sum = 2;
        while(!qu.empty()){
            int n = qu.size();
            for(int i = 1; i <= n; ++ i){
                string t = qu.front();
                qu.pop();
                if(t == endWord) return sum;
                addnext(t, qu, wordList);
            }
            sum++;
        }
        return 0;
    }
};

双向bfs
双向bfs,比单向更快,没有用queue,用了unorder set一样可以做,每次结束就装换,开两个,一头一尾,这题十分考验打码能力,非思维能力,2刷值得继续练习!

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        unordered_set<string> head, tail, *phead, *ptail;
        head.insert(beginWord);
        tail.insert(endWord);
        int sum = 2;
        while(!head.empty() && !tail.empty()){
            if(head.size() < tail.size()){
                phead = &head;
                ptail = &tail;
            }
            else{
                phead = &tail;
                ptail = &head;
            }
            unordered_set<string> temp;
            for(auto it = phead -> begin(); it != phead -> end(); it++){
                string word = *it;
                wordList.erase(word);
                for(int i = 0; i < word.length(); ++ i){
                    char t = word[i];
                    for(int j = 0; j < 26; ++ j){
                        word[i] = 'a' + j;
                        if(ptail -> find(word) != ptail -> end())
                            return sum;
                        if(wordList.find(word) != wordList.end()){
                            temp.insert(word);
                            wordList.erase(word);
                        }
                    }
                    word[i] = t;
                }
            }
            sum++;
            swap(*phead, temp);
        }
        return 0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值