国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

127. Word Ladder

2019-11-10 20:21:33
字體:
來源:轉載
供稿:網(wǎng)友

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.

給出一個開始單詞和結束單詞,以及一系列的轉換單詞,問最少幾次轉換能使開始單詞轉換成結束單詞。這里主要用到3個unordered_set<string>類型的集合,其中2個用來存放從兩端“延伸”出來的單詞(beginSet和endSet),還有一個存放剩余的單詞(wordSet)。為了減少計算時間,每次選擇元素個數(shù)比較少的集合(beginSet和endSet)進行操作,操作的集合設為set1,另一個為set2。對set1每一個單詞的每一個字母進行改變(每個字每改變26次),每次改變在set2中查找是否有當前單詞,如果有的話說明兩個集合能“連通”了,就返回答案;另外還要在wordSet中查找是否有該單詞,有的話收集起來(放在set3中),本輪結束后令set1変為set3(因為原本的單詞已經(jīng)沒用了,總不能變回去啦),收集之外還要在wordSet中刪除該單詞。初始答案為2,每輪操作答案都加2。要注意的是如果wordSet中不含結束單詞是無法完成轉換的,這種情況返回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;	}};


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 神农架林区| 雷波县| 淳安县| 普格县| 凭祥市| 专栏| 桑植县| 望都县| 黑河市| 桂平市| 澄城县| 繁峙县| 吉林省| 文登市| 沈丘县| 栾川县| 新密市| 开鲁县| 汽车| 聊城市| 萨迦县| 广宁县| 临海市| 阿坝| 宜都市| 天门市| 科尔| 抚远县| 公主岭市| 德江县| 嘉黎县| 枝江市| 江都市| 独山县| 德兴市| 峨边| 新和县| 大田县| 威宁| 云龙县| 绿春县|