[leetcode] 269. Alien Dictionary 解题报告
2016-03-25 15:58
447 查看
题目链接: https://leetcode.com/problems/alien-dictionary/
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new
language. Derive the order of letters in this language.
For example,
Given the following words in dictionary,
The correct order is:
Note:
You may assume all letters are in lowercase.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
思路: 真是麻烦的一笔的题, 让我想起当年写poj 1001的时候.
使用拓扑排序来解决这题吧. 用两个hash表, 一个来存每个出现过的字符的入度, 另一个来存一个字符指向的字符集合, 即一个字符应该在另外字符的前面. 然后就每次找出一个入度为0的字符, 并且更新这个字符指向的字符集入度减1. 如果还没有遍历完所有的字符, 但是找不到入度为0的字符了,那么说明无法排序, 返回"". 有一些情况就是可能一次会有几个入度为0的字符, 这样其实是没有严格的顺序的对这些字符, 这种情况就随便哪个都行.
代码如下:
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new
language. Derive the order of letters in this language.
For example,
Given the following words in dictionary,
[ "wrt", "wrf", "er", "ett", "rftt" ]
The correct order is:
"wertf".
Note:
You may assume all letters are in lowercase.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
思路: 真是麻烦的一笔的题, 让我想起当年写poj 1001的时候.
使用拓扑排序来解决这题吧. 用两个hash表, 一个来存每个出现过的字符的入度, 另一个来存一个字符指向的字符集合, 即一个字符应该在另外字符的前面. 然后就每次找出一个入度为0的字符, 并且更新这个字符指向的字符集入度减1. 如果还没有遍历完所有的字符, 但是找不到入度为0的字符了,那么说明无法排序, 返回"". 有一些情况就是可能一次会有几个入度为0的字符, 这样其实是没有严格的顺序的对这些字符, 这种情况就随便哪个都行.
代码如下:
class Solution { public: string alienOrder(vector<string>& words) { if(words.size() ==0) return ""; unordered_map<char, unordered_set<char>> table; unordered_map<char, int> indegree; string result; for(auto str: words) for(auto ch: str) indegree[ch] = 0; for(int i =0; i< words.size()-1; i++) { int x = 0; while(words[i+1][x] == words[i][x]) x++; if(x < words[i].size()) { if(table[words[i][x]].count(words[i+1][x]) ==0) { table[words[i][x]].insert(words[i+1][x]); indegree[words[i+1][x]]++; } } } for(int i = 0; i< indegree.size(); i++) { char ch = ' '; for(auto &val: indegree) if(val.second == 0) ch = val.first; if(ch == ' ') return ""; indegree[ch]--; for(auto &val: table[ch]) indegree[val]--; result += ch; } return result; } };
相关文章推荐
- 微服务(二)
- 转载 -- iOS数据持久化存储
- JMeter学习(十二)JMeter学习参数化User Defined Variables与User Parameters
- .NET中删除空白字符串的10大方法
- 执行构造的顺序
- jQuery监听文件上传实现进度条效果
- 在 JavaScript 中判断用户是用手机还是电脑打开此网页
- 给定一字符串,将每个单词的字符顺序倒置,单词间的顺序不变。例如:输入字符串“I love you”,输出“I evol uoy”。
- RTCP RTP报文结构
- 某A电面的详细解释
- 记php和java中英文字节长度和编码关系
- 1.4.1(extra)
- 1.4.2(extra)
- commonUtils简单总结
- 有逼格地判断数组是否为空
- 联通3G APN设置
- 合并表记录
- 实验一 操作系统模仿cmd
- netty 并发访问测试配置
- 设置网站expires和max-age属性