Word Ladder**
2015-09-03 13:03
267 查看
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start =
end =
dict =
As one shortest transformation is
return its length
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
Analyse: Refered to this.
Runtime: 276ms.
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start =
"hit"
end =
"cog"
dict =
["hot","dot","dog","lot","log"]
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.
Analyse: Refered to this.
Runtime: 276ms.
class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { wordDict.insert(endWord); //consider the string set as a graph queue<pair<string, int> > q; q.push(make_pair(beginWord, 1)); //start from the beginWord while(!q.empty()){ string s = q.front().first; //string to be compared int result = q.front().second; //the length of the ladder if(s == endWord) return result; //reach to the last string q.pop(); vector<string> neighbours = findNeighbours(s, wordDict); //find all neighbour string to the s for(int i = 0; i < neighbours.size(); i++) q.push(make_pair(neighbours[i], result + 1)); } return 0; } vector<string> findNeighbours(string s, unordered_set<string>& wordDict){ vector<string> result; for(int i = 0; i < s.length(); i++){ char temp = s[i]; for(int j = 0; j < 26; j++){// O(26 * s.length()) if(temp == 'a' + j) continue; //if the character is the same, then move to the next character s[i] = 'a' + j; if(wordDict.find(s) != wordDict.end()){ result.push_back(s); wordDict.erase(s); } } s[i] = temp; } return result; } };
相关文章推荐
- poj 2411 Mondriaan's Dream (轮廓线DP)
- ubuntu14.04安装GTX850M显卡驱动实录
- HTTP协议总结
- Java枚举类
- 【C/C++学院】0730-网站以及后门/结构体对齐、结构体面试分析/深拷贝与浅拷贝/队列/字符串封装
- leetcode: (136) Single Number
- Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码分析
- 自学QT之自己写一个窗口
- mongodb2.6部署副本集+分区
- 消息摘要算法---加密学习笔记(二)
- 消息摘要算法---加密学习笔记(二)
- HDU1532Drainage Ditches(网络流入门+EK模板题)
- BadgeView源码分析
- Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析
- Nginx负载均衡和LVS负载均衡的比较分析
- top命令
- java中的线程同步问题 模拟出售火车票
- 负载均衡调度算法
- Eclipse Debug的一些用法
- Android系统进程间通信(IPC)机制Binder中的Server启动过程源代码分析