[CareerCup] 18.10 Word Transform 单词转换
2024-10-13 19:18:44
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 Distance和Edit 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 {};
}
类似题目:
最新文章
- Android—Socket中关闭IO流后导致Socket关闭不能再收发数据的解决办法
- <;记录学习>;(前三天)京东页面各种注意点
- 65行 JavaScript 代码实现 Flappy Bird 游戏
- ABAP遇到的问题——1
- 乌龟棋(noip2010)
- IGS_学习笔记03_Integrated SOA Gateway设定配置(案例)
- Linux系统下安装rz/sz命令及使用说明(转载)
- hdu 5612 Baby Ming and Matrix games
- ongl 表达式
- 记2014“蓝桥杯全国软件大赛&;quot;决赛北京之行
- NYOJ 417 死神来了 鸽巢原理
- Oracle 中的SELECT 关键字(查询、检索)
- 入门html第一次copy小米首页布局
- 【转】【fiddler】抓取https数据失败,全部显示“Tunnel to......443”
- Pandas学习2 --- 数据类型Series、DataFrame
- Luogu4886 快递员 点分治
- php文件处理函数
- 10.Ubuntu操作系统及python2.7、3.5 exe
- 鼠标增强软件StrokeIt使用方法
- python模块--config
热门文章
- Unity3d 提示 ";The scripts file name does not match the name of the class defined in the script!";的解决办法
- Socket通信客户端设计(Java)
- Android studio导入eclipse项目且不改变目录结构
- DOM、Window对象操作
- hdu 3037 Saving Beans Lucas定理
- clone github的代码
- Linux解压文件
- poj 1651 Multiplication Puzzle (区间dp)
- Oracle PL/SQL设置快捷键的方法
- hdu 5072 Coprime 容斥原理