18. Word Ladder && Word Ladder II

时间:2021-11-23 09:50:34

Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. 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.

思想:宽度优先搜索(BFS)即可。(可从头往尾部搜,也可从尾往头部搜,)。

我的方案中,使用两个 hash_set 分别存储当前层和下一层结点,另一个 hash_set存储之前遍历过的结点。

class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
int ans = 0;
unordered_set<string> previousNodes;
vector<unordered_set<string> > node_levels(2);
int curLevel = 0; // which is index belong to vector node_levels.
node_levels[curLevel].insert(end);
ans++;
unordered_set<string>::iterator it;
while(!node_levels[curLevel].empty()) {
for(it = node_levels[curLevel].begin(); it != node_levels[curLevel].end(); ++it) {
for(size_t i = 0; i < it->size(); ++i) {
string node(*it);
for(node[i] = 'a'; node[i] <= 'z'; ++node[i]) {
if(node == start) return (ans+1); // output 1
if(previousNodes.count(node) || node_levels[curLevel].count(node) || node[i] == (*it)[i] || !dict.count(node))
continue;
node_levels[!curLevel].insert(node);
}
}
previousNodes.insert(*it);
}
node_levels[curLevel].clear();
curLevel = !curLevel;
ans++;
}
return 0; // output 2
}
};

Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given: start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"]

Return

  [
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]

Note:

  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

思想: 在 I 的基础之上, 加入 hash_map 记下每条边, 从 end 开始搜索,建立以 start 为源点,end 为汇点的图,然后从 start 开始深搜即可。

typedef pair<string, string> PAIR;
void getSolution(string &end, string& word, unordered_multimap<string, string> &map, vector<vector<string> > &vec, vector<string> &vec2) {
if(word == end) {
vec.push_back(vec2);
vec.back().push_back(word);
return;
}
pair<unordered_map<string, string>::iterator, unordered_map<string, string>::iterator> ret;
ret = map.equal_range(word);
while(ret.first != ret.second) {
vec2.push_back(ret.first->first);
getSolution(end, ret.first->second, map, vec, vec2);
vec2.pop_back();
ret.first++;
}
}
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> vec;
unordered_multimap<string, string> edges;
unordered_set<string> previousNodes;
vector<unordered_set<string> > node_levels(2);
int curLevel = 0; // an index belong to vector node_levels
node_levels[curLevel].insert(end);
unordered_set<string>::iterator it;
while(!node_levels[curLevel].empty() && node_levels[curLevel].count(start) == 0) {
for(it = node_levels[curLevel].begin(); it != node_levels[curLevel].end(); ++it) {
for(size_t i = 0; i < it->size(); ++i) {
string node(*it);
for(node[i] = 'a'; node[i] <= 'z'; ++node[i]) {
if(node == start) {
node_levels[1-curLevel].insert(node);
edges.insert(PAIR(start, *it));
break;
}
if(previousNodes.count(node) || node_levels[curLevel].count(node) || dict.count(node) == 0)
continue;
node_levels[1-curLevel].insert(node);
edges.insert(PAIR(node, *it));
}
}
previousNodes.insert(*it);
}
node_levels[curLevel].clear();
curLevel = !curLevel;
}
previousNodes.clear();
if(node_levels[curLevel].empty()) return vec;
vector<string> vec2;
getSolution(end, start, edges, vec, vec2);
return vec;
}
};

18. Word Ladder && Word Ladder II的更多相关文章

  1. Microsoft&period;Office&period;Interop&period;Word 创建word

    Microsoft.Office.Interop.Word 创建word 转载:http://www.cnblogs.com/chenbg2001/archive/2010/03/14/1685746 ...

  2. reverse the string word by word

    题目:Given an input string, reverse the string word by word. For example,Given s = "the sky is bl ...

  3. LeetCode 5&colon;Given an input string&comma; reverse the string word by word&period;

    problem: Given an input string, reverse the string word by word. For example: Given s = "the sk ...

  4. C&num;用Microsoft&period;Office&period;Interop&period;Word进行Word转PDF的问题

    之前用Aspose.Word进行Word转PDF发现'\'这个字符会被转换成'¥'这样的错误,没办法只能换个方法了.下面是Microsoft.Office.Interop.Word转PDF的方法: p ...

  5. &lbrack;CareerCup&rsqb; 18&period;7 Longest Word 最长的单词

    5.7 Given a list of words, write a program to find the longest word made of other words in the list. ...

  6. 17&period; Word Break &amp&semi;&amp&semi; Word Break II

    Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...

  7. LeetCode之&OpenCurlyDoubleQuote;动态规划”:Word Break &amp&semi;&amp&semi; Word Break II

     1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...

  8. leetcode&commat; &lbrack;139&sol;140&rsqb; Word Break &amp&semi; Word Break II

    https://leetcode.com/problems/word-break/ Given a string s and a dictionary of words dict, determine ...

  9. leetcode&commat; &lbrack;79&sol;140&rsqb; Trie树应用 Word Search &sol; Word Search II

    https://leetcode.com/problems/word-search/ class Solution { public: struct Trie{ Trie *next[]; bool ...

随机推荐

  1. SQL利用临时表实现动态列、动态添加列

    --方法一--------------------------------------------------------------------- declare @sql as varchar(1 ...

  2. chromedriver 与 chrome关联关系

    ----------ChromeDriver v2.22 (2016-06-06)---------- Supports Chrome v49-52 Resolved issue 1348: Time ...

  3. qt新进程工作目录的设置(工作目录确实是被子进程继承的,但也可以设置)

    经过试验,qt启动一个新的进程时,这个进程的工作目录是继承父进程的,无论是通过start还是startDetached来启动. 其实对于linux系统,qt底层应该也是调用fork.exec之类的函数 ...

  4. PHP程序员的技术成长规划(转)

    按照了解的很多PHP/LNMP程序员的发展轨迹,结合个人经验体会,抽象出很多程序员对未来的迷漫,特别对技术学习的盲目和慌乱,简单梳理了这个每个阶段PHP程序员的技术要求,来帮助很多PHP程序做对照设定 ...

  5. --&commat;angularJS--&dollar;scope&period;watch监听模型变化

    $watch简单使用 $watch是一个scope函数,用于监听模型变化,当你的模型部分发生变化时它会通知你. $watch(watchExpression, listener, objectEqua ...

  6. 【算法导论】B树

          一棵B树T是具有如下性质的有根树(设根为root): 1.每个节点x有一下域: (a)num,当前存储在节点x的关键字个数,关键字以非降序存放,因此key[i]<=key[i+1]& ...

  7. linux 查看命令总结

    1.tail -f -n 200 cat.log 2.使用less命令 less all.2018092510.0.log 打开log文件,默认显示100行记录. 输入/CustGroupListSe ...

  8. MySQLdb模块&lpar;数据库&rpar;

    安装 pip install mysqlclient 连接数据库 db = MySQLdb.connect(host="IP",port=端口,user="账号&quot ...

  9. 使用spring-rabbit测试RabbitMQ消息确认&lpar;发送确认&comma;接收确认&rpar;

    1.首先是rabbitmq的配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ...

  10. 如何使用vuejs过滤器

    大家再使用vue做项目时,查询功能当然必不可少,这就得使用vue强大的filter啦.其实vue内置的两个属性filterBy和orderBy已经能满足部分需求了,但是她更大的的魅力在于自定义filt ...