#120 Word ladder
来源:互联网 发布:汤姆叔叔 javascript 编辑:程序博客网 时间:2024/05/16 15:45
题目描述:
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
Notice
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
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
.
寻求path的问题,在我看来dfs和bfs都可以。此题为寻找最短路径,有两种方法:dfs求出所有符合条件的路径,然后取最小值;bfs直接求得的是最短路径之一。此题用dfs会在dict较大时超时,而题目只是要求最短路径,所以bfs为最佳答案。
Mycode (AC = 252ms):
class Solution {public: /** * @param start, a string * @param end, a string * @param dict, a set of string * @return an integer */ int ladderLength(string start, string end, unordered_set<string> &dict) { // write your code here // consider the special case if (start == end) return 1; // add start/end into dict, in case dict doesn't contain them dict.insert(start); dict.insert(end); // bfs to search the smallest length queue<string> str_queue; queue<int> levels; str_queue.push(start); levels.push(1); while (!str_queue.empty()) { string crt = str_queue.front(); str_queue.pop(); int level = levels.front(); levels.pop(); vector<string> next_words = getNextWord(crt, dict); for (int i = 0; i < next_words.size(); i++) { string word = next_words[i]; if (word == end) { return level + 1; } else { dict.erase(dict.find(word)); str_queue.push(word); levels.push(level + 1); } } } return 0; } // get the next word that in the dict vector<string> getNextWord(string crt, unordered_set<string> &dict) { vector<string> next_word; for (int i = 0; i < crt.length(); i++) { for (char ch = 'a'; ch <= 'z'; ch++) { string tmp = crt; tmp[i] = ch; if (tmp != crt && dict.find(tmp) != dict.end()) { next_word.push_back(tmp); } } } return next_word; }};
0 0
- #120 Word ladder
- Word Ladder
- Word Ladder
- word ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- webdriver实现2个或两个以上窗口间切换的方法
- java中正则模糊匹配字符串
- java编程查找质数代码优化
- ArcGIS Engine栅格数据使用总结
- 研究两天python函数式编程的总结和心得
- #120 Word ladder
- Java.Web学习笔记 JSTL
- ThinkPHP 3.1.2 查询方式
- JavaWeb学习总结(使用Session防止表单重复提交)
- 博弈论 来来来 套路一波(ACM中SG函数应用)
- Android(开源项目) 滑动选择器 WheelView 源码
- iOS 判断网址、链接地址、url地址是否可用
- 利用millis()实现Arduino定时器功能
- Java.Web学习笔记 自定义标签