[LeetCode]Word Ladder
2015-06-02 19:55
330 查看
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord toendWord, 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.
[LeetCode Source]
思路:这个题目要用到BFS,图论的解法。就是无权最短路径问题。
我们从一个点开始搜索,每次扩展一层,直到找到最后的单词。
我们采用两个队列,一个队列存储距离,另一个队列存储单词。
每次遍历到一个点后要将该点从Dict中删除掉,一种方法是遍历Dict找到相邻的点,
第二种是生成一个单词所有相邻单词然后搜寻。第一种方法会超时。
特别注意对Set操作时,如果采用erase会让原来的迭代器失败。比如:
最后AC的代码。这个时间依然有点长还可以改进。
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.
[LeetCode Source]
思路:这个题目要用到BFS,图论的解法。就是无权最短路径问题。
我们从一个点开始搜索,每次扩展一层,直到找到最后的单词。
我们采用两个队列,一个队列存储距离,另一个队列存储单词。
每次遍历到一个点后要将该点从Dict中删除掉,一种方法是遍历Dict找到相邻的点,
第二种是生成一个单词所有相邻单词然后搜寻。第一种方法会超时。
特别注意对Set操作时,如果采用erase会让原来的迭代器失败。比如:
for(auto it=wordDict.begin();it!=wordDict.end();++it){ if(next(now,*it)){ dis.push(distance+1); q.push(*it); wordDict.erase(it); } }这样编译的确通过,但是会出现运行时错误,原因在于erase之后原来迭代次失效了,导致这个循环出错,一定要避免。
最后AC的代码。这个时间依然有点长还可以改进。
class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { queue<string> q; q.push(beginWord); queue<int> dis; dis.push(1); wordDict.erase(beginWord); while(!q.empty()){ string now = q.front(); int distance = dis.front(); if(now==endWord) return distance; q.pop(); dis.pop(); for(int i=0;i<now.size();++i){ for(char j='a';j<='z';++j){ char rec = now[i]; now[i] = j; if(wordDict.find(now)!=wordDict.end()) { q.push(now); dis.push(distance+1); wordDict.erase(now); } now[i] = rec; } } } return 0; } };
相关文章推荐
- HDU 2227 Find the nondecreasing subsequences(DP)
- Lucene 高亮功能
- 第七章第六题
- MVC开发Markdown编辑器(2)
- List<T>做数据源绑定的问题
- qt里面如何调用mplayer
- poj1936(简单题,串)
- HDFS原理解析(总体架构,读写操作流程及源码查看等)
- jquery根据特定的值设置 input type=radio 单选框为选中状态
- 安卓加载动画崩溃
- 最长回文子串
- 实现挂号收费的收费录入功能的代码(九)
- chrome空间自动点赞插件。浏览器插件简单例子。
- 最近找实习的一些感悟
- 多线程学习 + o2o简识
- leetcode Palindrome Partitioning
- 客运综合管理系统项目—报班统计(员工报班)
- 第七章第五题
- 【转】style、id、class和*的优先级
- iOS symbol化的多种方式