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. php多关键字查询

      php单一关键字查询 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 tdansitional//EN" "http: ...

  2. ManualResetEvent知识总结

    一. 用法概述 Manual发音:英[ˈmænjuəl] 直译,手动重置事件 开发者的可以手动对线程间的交互进行手动控制. 二.构造函数 构造函数,如果为 true,则将初始状态设置为终止:如果为 f ...

  3. PyQt4入门学习笔记(四)

    在PyQt4中的事件和信号 事件 所有的GUI应用都是事件驱动的.事件主要是来自于应用的使用者,但是像互联网连接,窗口管理器或者计时器也可以产生事件.当我们调用应用的exec_()方法时,应用就进入了 ...

  4. dpkg:处理软件包dradis (--configure)时出错

    dpkg:处理软件包dradis (--configure)时出错!解决方案:1.将info文件夹更名%mv /var/lib/dpkg/info /var/lib/dpkg/info_old2.新建 ...

  5. Python 历遍目录

    Automate the Boring Stuff 学习笔记 01 使用 os 模块的 walk() 函数可以实现历遍目录的操作,该函数接收一个绝对路径字符串作为必选参数,返回三个参数: 当前目录—— ...

  6. GJM : Unity3D HIAR -【 快速入门 】 四、创建 Hello World

    创建 Hello World 本文将介绍如何在 Windows 系统下,使用 HiAR SDK 创建一个简单的 AR 应用.在开始之前,请先完成下列准备工作: 注册 HiAR 帐户 获取 AppKey ...

  7. 微信小程序社区上线

    微信小程序公测了! 从首次得到微信小程序发布的消息开始,小木和Michael就进入了紧急备战状态. 除了要快速学通微信小程序开发之外,我们还做了这些工作: 1.录制全球首套微信小程序实战项目类视频教程 ...

  8. 【原】JAVA开发环境搭建

    1.JDK下载并安装,以jdk-7u45-windows-i586.exe为例(注意JDK的安装和JRE的安装是分开的) 2.“我的电脑”右键属性,找到“高级系统设置”,找到“高级”tab下的“环境变 ...

  9. 谈谈我对前端组件化中“组件”的理解,顺带写个Vue与React的demo

    前言 前端已经过了单兵作战的时代了,现在一个稍微复杂一点的项目都需要几个人协同开发,一个战略级别的APP的话分工会更细,比如携程: 携程app = 机票频道 + 酒店频道 + 旅游频道 + ..... ...

  10. GreenDao2.2升级GreenDao3.0的适配之路

    前言.为什么要升级到Greendao3.0? 1. 多人开发 以往的数据库建表建Dao等操作要新开一个module,在统一的地方管理数据库建表,现在可以直接写Entity.多人开发时自己管自己的Ent ...