[LeetCode] 127. Word Ladder

来源:互联网 发布:布朗肖 知乎 编辑:程序博客网 时间:2024/05/16 14:31

思路:
BFS. 挺复杂的, 看了https://discuss.leetcode.com/topic/16983/easy-76ms-c-solution-using-bfs的介绍. 主要就是拿到一个word以后要在原来的set里面找到所有和他只差一个字符的word, push到队列里面, 然后看有没有某个word和endWord相等了.

void addWords(string& beginWord, unordered_set<string>& wordList, queue<string>& nextLayer) {    wordList.erase(beginWord);    for (int i = 0; i < beginWord.length(); i++) {        char tempC = beginWord[i];        for (char c = 'a'; c <= 'z'; c++) {            if (beginWord[i] == c)                continue;            beginWord[i] = c;            if (wordList.find(beginWord) != wordList.end()) {                nextLayer.push(beginWord);                wordList.erase(beginWord);                  }        }        beginWord[i] = tempC;    }}int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {    queue<string> nextLayer;    addWords(beginWord, wordList, nextLayer);    int res = 2;    while (! nextLayer.empty()) {        int size = nextLayer.size();        for (int i = 0; i < size; i++) {            string curWord = nextLayer.front();            nextLayer.pop();            if (curWord == endWord)                return res;            addWords(curWord, wordList, nextLayer);        }        res++;    }    return 0;}

第二种方法, 前后两头向中间加.

int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {    wordList.erase(beginWord);    wordList.erase(endWord);    unordered_set<string> frontToBack;    unordered_set<string> backToFront;    frontToBack.insert(beginWord);    backToFront.insert(endWord);    int res = 2, len = beginWord.length();    while (! frontToBack.empty()) {        if (frontToBack.size() > backToFront.size())             swap(frontToBack, backToFront);        unordered_set<string> tempSet;        unordered_set<string>::iterator it = frontToBack.begin();        for ( ; it != frontToBack.end(); it++) {            string curWord = *it;            for (int i = 0; i < curWord.size(); i++) {                int tempC = curWord[i];                for (char c = 'a'; c <= 'z'; c++) {                    if (c == tempC) continue;                    curWord[i] = c;                    if (backToFront.find(curWord) != backToFront.end())                        return res;                    if (wordList.find(curWord) != wordList.end()) {                        tempSet.insert(curWord);                        wordList.erase(curWord);                    }                }                curWord[i] = tempC;            }        }        swap(frontToBack, tempSet);        res++;    }    return 0;}
0 0
原创粉丝点击