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] 269. 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] Alien Dictionary 另类字典

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

  4. [leetcode]269. Alien Dictionary外星字典

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

  5. LeetCode 269. Alien Dictionary

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

  6. 269. Alien Dictionary火星语字典(拓扑排序)

    [抄题]: There is a new alien language which uses the latin alphabet. However, the order among letters ...

  7. 269. Alien Dictionary

    题目: There is a new alien language which uses the latin alphabet. However, the order among letters ar ...

  8. [Locked] Alien Dictionary

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

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

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

随机推荐

  1. 【mysql报错】MySQL host is blocked because of many connection errors; 解决方法

    MySQL host is blocked because of many connection errors; 报错 环境 操作系统:Linux 数据库:mysql5.7.27 错误提示 jHost ...

  2. html点击弹出QQ添加好友的窗口

    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1377732948&q ...

  3. 分布式应用的未来 — Distributionless

    作者丨阿里云高级技术专家 至简(李云) 在技术变革推动社会发展这一时代背景下,大量支撑规模化分布式应用的技术创新.创造与创业应用而生,Could Native.Service Mesh.Serverl ...

  4. JWT简要说明

    什么是JWT? JSON Web Token (JWT) 是一种开放标准 (RFC 7519) 定义了一种用于安全传输的紧凑.自包含(注:或自说明) 的Json结构, 被传输的信息可以通过JWT内容中 ...

  5. 3、Ext.NET 1.7 官方示例笔记-表单

    表单[Form],就是向客户收集资料的窗口,用户在表单填写好各种信息,然后提交到服务器,服务器接收并保存到数据库里. 表单的字段类型很多,我们从最简单的开始吧. 1.1 .先开始组合框吧(ComboB ...

  6. 跨域问题 Blocked a frame with origin "http://......" from accessing a cross-origin frame.

    为了轻松偷懒,不想从目的项目中开发目标项目中的页面,但目的项目中需要获取老项目中的页面,这里用了iframe跨域链接页面出现了问题 Blocked a frame with origin " ...

  7. 学习shiro第一天

    shiro是一个强大而且易用的安全框架(主要包括认证和授权),它比spring security更加简单,而且它不依赖于任何容器,可以和许多框架集成. shiro的核心是安全管理器(SecurityM ...

  8. Java中的参数验证(非Spring版)

    1. Java中的参数验证(非Spring版) 1.1. 前言 为什么我总遇到这种非正常问题,我们知道很多时候我们的参数校验都是放在controller层的传入参数进行校验,我们常用的校验方式就是引入 ...

  9. Python语言基础07-面向对象编程基础

    本文收录在Python从入门到精通系列文章系列 1. 了解面对对象编程 活在当下的程序员应该都听过"面向对象编程"一词,也经常有人问能不能用一句话解释下什么是"面向对象编 ...

  10. Shiro RememberMe 1.2.4 反序列化漏洞复现

    目录 原理解释 环境搭建 复现过程 原理解释   Apache Shiro是一个Java安全框架,执行身份验证.授权.密码和会话管理.   shiro默认使用了CookieRememberMeMana ...