18. Word Ladder && Word Ladder II
Word Ladder
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
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:
- 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"]
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的更多相关文章
- Microsoft.Office.Interop.Word 创建word
Microsoft.Office.Interop.Word 创建word 转载:http://www.cnblogs.com/chenbg2001/archive/2010/03/14/1685746 ...
- reverse the string word by word
题目:Given an input string, reverse the string word by word. For example,Given s = "the sky is bl ...
- LeetCode 5:Given an input string, reverse the string word by word.
problem: Given an input string, reverse the string word by word. For example: Given s = "the sk ...
- C#用Microsoft.Office.Interop.Word进行Word转PDF的问题
之前用Aspose.Word进行Word转PDF发现'\'这个字符会被转换成'¥'这样的错误,没办法只能换个方法了.下面是Microsoft.Office.Interop.Word转PDF的方法: p ...
- [CareerCup] 18.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. ...
- 17. Word Break && Word Break II
Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...
- LeetCode之“动态规划”:Word Break && Word Break II
1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...
- leetcode@ [139/140] Word Break & Word Break II
https://leetcode.com/problems/word-break/ Given a string s and a dictionary of words dict, determine ...
- leetcode@ [79/140] Trie树应用 Word Search / Word Search II
https://leetcode.com/problems/word-search/ class Solution { public: struct Trie{ Trie *next[]; bool ...
随机推荐
- c# mvc使用 npoi下载 excel
IWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一个sheet ISheet sheet1 = book.CreateShee ...
- [转]Web3.0时代,企业知识管理新趋势
[转自http://www.amt.com.cn/html/ManageFront/AMTPoint0/2014/0716/1370.html] Web3.0时代,企业知识管理新趋势 2014-07- ...
- 一台服务器发布多个tomcat并注册服务名办法
修改服务名称 打开Tomcat7.0.65_1/bin/service.bat 修改注册服务名称 当然这个名字自己改 比如Tomcat7_2 原始文件: set SERVICE_NAME=Tom ...
- css盒子模型层级3D图
作为前端开发工程师,大家都应该知道盒子模型.下面用一张图来表达3D盒子模型的层级关系 大家可以看到background-color 在background-image的下一层.这个希望对大家有帮助
- Python学习笔记-字典
字典是python中唯一内建的映射类型. 创建字典phonebook = {'Alice':'2341','Beth':'9102'} 可以使用dict通过其他映射或者键值对的序列建立字典.关键值参数 ...
- Windows Server 2008(R2)配置apache+php+mysql环境问题事项
服务器环境:Windows 2008 R2 64位.apache,mysql,php都是32位. 1. 80端口的外网访问问题 表现:80端口本地可以访问,外网不能访问,换了8080端口也是一样,检查 ...
- web.xml在Servlet3.0中的新增元素
metadata-complete: 当属性为true时,该Web应用将不会加载注解配置的Web组件(如Servlet.Filter.Listener) 当属性为false时,将加载注解配置的Web组 ...
- OD调试篇6--对一些真正的小程序进行一点点的修改
先打开这个程序看看,提醒你这是一个未注册版本的软件.会发现只能添加4个联系人,这显然是我不想看见的,于是我要对这个程序进行一些修改,嘿嘿... 通过OD载入这个程序 有一些(SEH)也就是异常,我们可 ...
- 【转】精心推荐几款超实用的 CSS 开发工具
原文转自:http://www.html5cn.org/article-5741-1.html 摘要: 当你开发一个网站或 Web 应用程序的时候,有合适的工具,绝对可以帮助您节省大量的时间.在这篇文 ...
- Sublime Text 快捷键及插件安装
Sublime Text是一款跨平台的编辑器,它小巧绿色且速度非常快,支持各种流行编程语言的语法高亮.代码补全等,插件非常丰富!editplus.notepad++也都是不错的工具,体积轻巧,启动迅速 ...