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 non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Example 1:

Input:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
] Output: "wertf"

Example 2:

Input:
[
"z",
"x"
] Output: "zx"

Example 3:

Input:
[
"z",
"x",
"z"
] Output: ""  Explanation: The order is invalid, so return "".

Note:

  1. You may assume all letters are in lowercase.
  2. You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
  3. If the order is invalid, return an empty string.
  4. There may be multiple valid order of letters, return any one of them is fine.

这道题让给了一些按“字母顺序”排列的单词,但是这个字母顺序不是我们熟知的顺序,而是另类的顺序,让根据这些“有序”的单词来找出新的字母顺序,这实际上是一道有向图遍历的问题,跟之前的那两道 Course Schedule II 和 Course Schedule 的解法很类似,我们先来看 BFS 的解法,需要一个 TreeSet 来保存可以推测出来的顺序关系,比如题目中给的例子1,可以推出的顺序关系有:

t->f
w->e
r->t
e->r

这些就是有向图的边,对于有向图中的每个结点,计算其入度,然后从入度为0的结点开始 BFS 遍历这个有向图,然后将遍历路径保存下来返回即可。下面来看具体的做法:

根据之前讲解,需用 TreeSet 来保存这些 pair,还需要一个 HashSet 来保存所有出现过的字母,需要一个一维数组 in 来保存每个字母的入度,另外还要一个 queue 来辅助拓扑遍历,我们先遍历单词集,把所有字母先存入 HashSet,然后我们每两个相邻的单词比较,找出顺序 pair,然后根据这些 pair 来赋度,把 HashSet 中入度为0的字母都排入 queue 中,然后开始遍历,如果字母在 TreeSet 中存在,则将其 pair 中对应的字母的入度减1,若此时入度减为0了,则将对应的字母排入 queue 中并且加入结果 res 中,直到遍历完成,看结果 res 和 ch 中的元素个数是否相同,若不相同则说明可能有环存在,返回空字符串,参见代码如下:

解法一:

class Solution {
public:
string alienOrder(vector<string>& words) {
set<pair<char, char>> st;
unordered_set<char> ch;
vector<int> in();
queue<char> q;
string res;
for (auto a : words) ch.insert(a.begin(), a.end());
for (int i = ; i < (int)words.size() - ; ++i) {
int mn = min(words[i].size(), words[i + ].size()), j = ;
for (; j < mn; ++j) {
if (words[i][j] != words[i + ][j]) {
st.insert(make_pair(words[i][j], words[i + ][j]));
break;
}
}
if (j == mn && words[i].size() > words[i + ].size()) return "";
}
for (auto a : st) ++in[a.second];
for (auto a : ch) {
if (in[a] == ) {
q.push(a);
res += a;
}
}
while (!q.empty()) {
char c = q.front(); q.pop();
for (auto a : st) {
if (a.first == c) {
--in[a.second];
if (in[a.second] == ) {
q.push(a.second);
res += a.second;
}
}
}
}
return res.size() == ch.size() ? res : "";
}
};

下面来看一种 DFS 的解法,思路和 BFS 的很类似,需要建立一个二维的 bool 数组g,为了节省空间,不必像上面的解法中一样使用一个 HashSet 来记录所有出现过的字母,可以直接用这个二维数组来保存这个信息,只要 g[i][i] = true,即表示位置为i的字母存在。同时,这个二维数组还可以保存顺序对儿的信息,只要 g[i][j] = true,就知道位置为i的字母顺序在位置为j的字母前面。找顺序对儿的方法跟上面的解法完全相同,之后就可以进行 DFS 遍历了。由于 DFS 遍历需要标记遍历结点,那么就用一个 visited 数组,由于是深度优先的遍历,并不需要一定要从入度为0的结点开始遍历,而是从任意一个结点开始都可以,DFS 会遍历到出度为0的结点为止,加入结果 res,然后回溯加上整条路径到结果 res 即可,参见代码如下:

解法二:

class Solution {
public:
string alienOrder(vector<string>& words) {
vector<vector<bool>> g(, vector<bool>());
vector<bool> visited();
string res;
for (string word : words) {
for (char c : word) {
g[c - 'a'][c - 'a'] = true;
}
}
for (int i = ; i < (int)words.size() - ; ++i) {
int mn = min(words[i].size(), words[i + ].size()), j = ;
for (; j < mn; ++j) {
if (words[i][j] != words[i + ][j]) {
g[words[i][j] - 'a'][words[i + ][j] - 'a'] = true;
break;
}
}
if (j == mn && words[i].size() > words[i + ].size()) return "";
}
for (int i = ; i < ; ++i) {
if (!dfs(g, i, visited, res)) return "";
}
return res;
}
bool dfs(vector<vector<bool>>& g, int idx, vector<bool>& visited, string& res) {
if (!g[idx][idx]) return true;
visited[idx] = true;
for (int i = ; i < ; ++i) {
if (i == idx || !g[i][idx]) continue;
if (visited[i]) return false;
if (!dfs(g, i, visited, res)) return false;
}
visited[idx] = false;
g[idx][idx] = false;
res += 'a' + idx;
return true;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/269

类似题目:
 

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Alien Dictionary 另类字典的更多相关文章

  1. [LeetCode] 269. Alien Dictionary 另类字典

    There is a new alien language which uses the latin alphabet. However, the order among letters are un ...

  2. 269. Alien Dictionary 另类字典 *HARD*

    There is a new alien language which uses the latin alphabet. However, the order among letters are un ...

  3. [LeetCode] 269. Alien Dictionary 外文字典

    There is a new alien language which uses the latin alphabet. However, the order among letters are un ...

  4. LeetCode Alien Dictionary

    原题链接在这里:https://leetcode.com/problems/alien-dictionary/ 题目: There is a new alien language which uses ...

  5. Leetcode: Alien Dictionary && Summary: Topological Sort

    There is a new alien language which uses the latin alphabet. However, the order among letters are un ...

  6. [Locked] Alien Dictionary

    Alien Dictionary There is a new alien language which uses the latin alphabet. However, the order amo ...

  7. 设计一个 硬件 实现的 Dictionary(字典)

    Dictionary 就是 字典, 是一种可以根据 Key 来 快速 查找 Value 的 数据结构 . 比如 我们在 C# 里用到的 Dictionary<T>, 在 程序设计 里, 字 ...

  8. 【Leetcode_easy】953. Verifying an Alien Dictionary

    problem 953. Verifying an Alien Dictionary solution: class Solution { public: bool isAlienSorted(vec ...

  9. Verifying an Alien Dictionary

    2019-11-24 22:11:30 953. Verifying an Alien Dictionary 问题描述: 问题求解: 这种问题有一种解法是建立新的排序和abc排序的映射,将这里的str ...

随机推荐

  1. Eclipse 实用技巧

    代码智能提示 Java智能提示 Window -> Preferences -> Java -> Editor -> Content Assist -> Auto Act ...

  2. 在ASP.NET Core Web API上使用Swagger提供API文档

    我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...

  3. 【WP8.1】WebView笔记

    之前在WP8的时候做过WebBrowser相关的笔记,在WP8.1的WebView和WebBrowser有些不一样,在这里做一些笔记 下面分为几个部分 1.禁止缩放 2.JS通知后台C#代码(noti ...

  4. wampserver服务器无法启动(图标颜色不对)

    1.服务器一直无法启动,图标颜色一直显示黄色,并且不可用. 2.解决办法: (1) C:\wamp\bin\apache\apache2.4.9\bin ->httpd.exe  找到该文件 ( ...

  5. Angular通过XHR加载模板而限制使用file://(解决方案)

    编写angular项目时,遇到此困难: angular.js:12011 XMLHttpRequest cannot load file:///E:/angular/imooc/chapter2/bo ...

  6. 最小生成树计数 bzoj 1016

    最小生成树计数 (1s 128M) award [问题描述] 现在给出了一个简单无向加权图.你不满足于求出这个图的最小生成树,而希望知道这个图中有多少个不同的最小生成树.(如果两颗最小生成树中至少有一 ...

  7. 使用MyBatis Generator自动创建代码(dao,mapping,poji)

    连接的数据库为SQL server2008,所以需要的文件为sqljdbc4.jar 使用的lib库有: 在lib库目录下新建一个src文件夹用来存放生成的文件,然后新建generatorConfig ...

  8. Waud.js – 使用HTML5降级处理的Web音频库

    Waud.js 是一个Web音频库,有一个HTML5音频降级处理方案. 它允许您利用Web音频API为你的Web应用程序控制音频功能.在不支持Web音频API的非现代浏览器使用HTML5音频降级方案. ...

  9. (十四)Maven聚合与继承

    1.Maven聚合 我们在平时的开发中,项目往往会被划分为好几个模块,比如common公共模块.system系统模块.log日志模块.reports统计模块.monitor监控模块等等.这时我们肯定会 ...

  10. css选择器的使用详解

    -.css选择器的分类: 二.常用选择器详解: 1.标签选择器: 语法: 标签名 { 属性:属性值; } 代码示例: h1 { color: #ccc; font-size: 28px; } 2.类选 ...