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

首頁 > 學院 > 開發設計 > 正文

127. Word Ladder

2019-11-10 19:51:32
字體:
來源:轉載
供稿:網友

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)。為了減少計算時間,每次選擇元素個數比較少的集合(beginSet和endSet)進行操作,操作的集合設為set1,另一個為set2。對set1每一個單詞的每一個字母進行改變(每個字每改變26次),每次改變在set2中查找是否有當前單詞,如果有的話說明兩個集合能“連通”了,就返回答案;另外還要在wordSet中查找是否有該單詞,有的話收集起來(放在set3中),本輪結束后令set1変為set3(因為原本的單詞已經沒用了,總不能變回去啦),收集之外還要在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;	}};


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 荣成市| 泽普县| 玉山县| 固原市| 盖州市| 古浪县| 阿克| 广安市| 南昌市| 禹城市| 昭苏县| 阿拉善左旗| 柘城县| 连州市| 平远县| 玉田县| 焉耆| 文安县| 巴彦淖尔市| 抚州市| 吴江市| 尼勒克县| 汉寿县| 昌平区| 三亚市| 济源市| 荔波县| 凤凰县| 新巴尔虎右旗| 新和县| 城步| 鹤岗市| 泰兴市| 泉州市| 和龙市| 花莲市| 周宁县| 京山县| 广汉市| 合作市| 家居|