[LeetCode] Word Ladder 词语阶梯
2015-05-30 07:06
375 查看
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.
这道词句阶梯的问题给了我们一个单词字典,里面有一系列很相似的单词,然后给了一个起始单词和一个结束单词,每次变换只能改变一个单词,并且中间过程的单词都必须是单词字典中的单词,让我们求出最短的变化序列的长度。这道题还是挺有难度的,我当然是看了别人的解法才写出来的,这里用到了两个高级数据结构unordered_map和queue,即哈希表和队列,其中哈希表是记录单词和目前序列长度之间的映射,而队列的作用是保存每一个要展开的单词。首先把起始单词映射为1,把起始单词排入队列中,开始队列的循环,取出队首词,然后对其每个位置上的字符,用26个字母进行替换,如果此时和结尾单词相同了,就可以返回取出词在哈希表中的值加一。如果替换词在字典中存在但在哈希表中不存在,则将替换词排入队列中,并在哈希表中的值映射为之前取出词加一。如果循环完成则返回0,参见代码如下:
参考资料:
https://leetcode.com/discuss/11648/a-25-line-1204ms-bfs-solution
/article/4879661.html
LeetCode All in One 题目讲解汇总(持续更新中...)
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.
这道词句阶梯的问题给了我们一个单词字典,里面有一系列很相似的单词,然后给了一个起始单词和一个结束单词,每次变换只能改变一个单词,并且中间过程的单词都必须是单词字典中的单词,让我们求出最短的变化序列的长度。这道题还是挺有难度的,我当然是看了别人的解法才写出来的,这里用到了两个高级数据结构unordered_map和queue,即哈希表和队列,其中哈希表是记录单词和目前序列长度之间的映射,而队列的作用是保存每一个要展开的单词。首先把起始单词映射为1,把起始单词排入队列中,开始队列的循环,取出队首词,然后对其每个位置上的字符,用26个字母进行替换,如果此时和结尾单词相同了,就可以返回取出词在哈希表中的值加一。如果替换词在字典中存在但在哈希表中不存在,则将替换词排入队列中,并在哈希表中的值映射为之前取出词加一。如果循环完成则返回0,参见代码如下:
class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { unordered_map<string, int> m; queue<string> q; m[beginWord] = 1; q.push(beginWord); while (!q.empty()) { string word = q.front(); q.pop(); for (int i = 0; i < word.size(); ++i) { string newWord = word; for (char ch = 'a'; ch <= 'z'; ++ch) { newWord[i] = ch; if (newWord == endWord) return m[word] + 1; if (wordDict.find(newWord) != wordDict.end() && m.find(newWord) == m.end()) { q.push(newWord); m[newWord] = m[word] + 1; } } } } return 0; } };
参考资料:
https://leetcode.com/discuss/11648/a-25-line-1204ms-bfs-solution
/article/4879661.html
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- 君子周而不比,小人比而不周
- ubuntu 和windows双系统启动顺序的修改
- js常用函数、书写可读性的js、js变量声明...
- iOS中的事件
- Web Worker
- Windows Server 2012 路由和远程访问
- 面试分享(二)-------北京村村乐科技有限公司杭州分公司------Android开发
- arcPython细节汇总
- WEB_进来就给你想要的
- css-backgournd-position详解
- 面试分享(一)-------浙江元亨通信技术股份有限公司-------高级java开发
- HDU 1175 连连看【BFS】
- python中sorted实战应用
- 数组参数的sizeof
- Python中sorted()方法的用法
- java-策略模式
- 1.Two Sum
- Reseau Mobile移动网络跟从大到小
- 张家辉的肌肉怎么炼成的
- SNMP4J简介