Given two Words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord toendWord, such that:
Only one letter can be changed at a time.Each transformed word must exist in the word list. Note that beginWord isnot 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.UPDATE (2017/1/20):The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Subscribe to see which companies asked this question.
給出一個(gè)開始單詞和結(jié)束單詞,以及一系列的轉(zhuǎn)換單詞,問最少幾次轉(zhuǎn)換能使開始單詞轉(zhuǎn)換成結(jié)束單詞。這里主要用到3個(gè)unordered_set<string>類型的集合,其中2個(gè)用來存放從兩端“延伸”出來的單詞(beginSet和endSet),還有一個(gè)存放剩余的單詞(wordSet)。為了減少計(jì)算時(shí)間,每次選擇元素個(gè)數(shù)比較少的集合(beginSet和endSet)進(jìn)行操作,操作的集合設(shè)為set1,另一個(gè)為set2。對set1每一個(gè)單詞的每一個(gè)字母進(jìn)行改變(每個(gè)字每改變26次),每次改變在set2中查找是否有當(dāng)前單詞,如果有的話說明兩個(gè)集合能“連通”了,就返回答案;另外還要在wordSet中查找是否有該單詞,有的話收集起來(放在set3中),本輪結(jié)束后令set1変為set3(因?yàn)樵镜膯卧~已經(jīng)沒用了,總不能變回去啦),收集之外還要在wordSet中刪除該單詞。初始答案為2,每輪操作答案都加2。要注意的是如果wordSet中不含結(jié)束單詞是無法完成轉(zhuǎn)換的,這種情況返回0.
代碼:
class Solution{public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { using strset = unordered_set<string>; strset beginSet, endSet, wordSet(wordList.begin(), wordList.end()); if(wordSet.find(endWord) == wordSet.end()) return 0; beginSet.insert(beginWord); endSet.insert(endWord); wordSet.erase(endWord); int res = 2; while(!beginSet.empty() && !endSet.empty()) { strset *set1, *set2, set3; if(beginSet.size() <= endSet.size()) { set1 = &beginSet; set2 = &endSet; } else { set2 = &beginSet; set1 = &endSet; } for(auto iter = set1->begin(); iter != set1->end(); ++iter) { string cur = *iter; for(int i = 0; i < cur.size(); ++i) { char tmp = cur[i]; for(int j = 0; j < 26; ++j) { cur[i] = 'a' + j; if(set2->find(cur) != set2->end()) return res; if(wordSet.find(cur) != wordSet.end()) { set3.insert(cur); wordSet.erase(cur); } } cur[i] = tmp; } } swap(*set1, set3); ++res; } return 0; }};
新聞熱點(diǎn)
疑難解答