18.10 Given two words of equal length that are in a dictionary, write a method to transform one word into another word by changing only one letter at a time. The new word you get in each step must be in the dictionary.

这道题让我们将一个单词转换成另一个单词,每次只能改变一个字母,让我们输出中间转换过程的单词。LeetCode上有类似的题目One Edit DistanceEdit Distance。我们的方法是写一个get_one_edit_words()函数,来返回某一个单词变动一个字母的所有可能情况,然后我们在transform函数中先将开始的单词存入一个队列queue中,还需要一个set来记录所有访问过的单词,还需要哈希表来建立当前单词和变换一步后的单词之间的映射,然后开始类似BFS的遍历,对于每一个单词,遍历get_one_edit_words()函数返回的结果,如果变换后的单词就是目标单词,则我们完成了变换,根据backtrack将整个路径上的单词存入结果中,如果变换单词不是目标单词,但是在字典中,如果没有在字典中,则我们将其排入queue,并加入visited,和建立哈希表的映射,继续遍历,参见代码如下:

set<string> get_one_edit_words(string word) {
set<string> res;
for (int i = ; i < word.size(); ++i) {
string t = word;
for (char c = 'a'; c <= 'z'; ++c) {
if (c != word[i]) {
t[i] = c;
res.insert(t);
}
}
}
return res;
} vector<string> transform(string start, string end, set<string> dict) {
queue<string> q;
set<string> visited;
unordered_map<string, string> backtrack;
q.push(start);
visited.insert(start);
while (!q.empty()) {
string w = q.front(); q.pop();
for (string v : get_one_edit_words(w)) {
if (v == end) {
vector<string> res{v};
while (!w.empty()) {
res.insert(res.begin(), w);
w = backtrack[w];
}
return res;
}
if (dict.count(v)) {
if (!visited.count(v)) {
q.push(v);
visited.insert(v);
backtrack[v] = w;
}
}
}
}
return {};
}

类似题目:

One Edit Distance

Edit Distance

CareerCup All in One 题目汇总

最新文章

  1. Android—Socket中关闭IO流后导致Socket关闭不能再收发数据的解决办法
  2. &lt;记录学习&gt;(前三天)京东页面各种注意点
  3. 65行 JavaScript 代码实现 Flappy Bird 游戏
  4. ABAP遇到的问题——1
  5. 乌龟棋(noip2010)
  6. IGS_学习笔记03_Integrated SOA Gateway设定配置(案例)
  7. Linux系统下安装rz/sz命令及使用说明(转载)
  8. hdu 5612 Baby Ming and Matrix games
  9. ongl 表达式
  10. 记2014“蓝桥杯全国软件大赛&amp;quot;决赛北京之行
  11. NYOJ 417 死神来了 鸽巢原理
  12. Oracle 中的SELECT 关键字(查询、检索)
  13. 入门html第一次copy小米首页布局
  14. 【转】【fiddler】抓取https数据失败,全部显示“Tunnel to......443”
  15. Pandas学习2 --- 数据类型Series、DataFrame
  16. Luogu4886 快递员 点分治
  17. php文件处理函数
  18. 10.Ubuntu操作系统及python2.7、3.5 exe
  19. 鼠标增强软件StrokeIt使用方法
  20. python模块--config

热门文章

  1. Unity3d 提示 &quot;The scripts file name does not match the name of the class defined in the script!&quot;的解决办法
  2. Socket通信客户端设计(Java)
  3. Android studio导入eclipse项目且不改变目录结构
  4. DOM、Window对象操作
  5. hdu 3037 Saving Beans Lucas定理
  6. clone github的代码
  7. Linux解压文件
  8. poj 1651 Multiplication Puzzle (区间dp)
  9. Oracle PL/SQL设置快捷键的方法
  10. hdu 5072 Coprime 容斥原理