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,

[
"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.

分析:

  前后关系可看做是一种偏序关系,对于每个序列,可以看成是有向图,所有序列合在一起就成了一个大的有向图,本题可转换成有向图的拓扑排序,用BFS可解决。主要过程包含:1、根据string数组的信息映射成图;2、在图上计算出所有节点的入度;3、进行BFS,得到拓扑排序结果。故我用三个子函数来分别处理这三个过程。

代码:

//将string数组映射到图上,最坏时间复杂度就是每个字母遍历一遍,这也是必要,故也是最低时间复杂度
unordered_multimap<char, char> mapping(vector<string> &vs) {
//先处理第一列,用validcomp来记录哪些相邻行的值相等,用于后面的列的处理,不相等的就可以得偏序条件,用边来表示,存入edges中;然后处理第二列,以此类推。
unordered_multimap<char, char> edges;
unordered_set<int> validcomp, temp;
for(int i = ; i < vs.size(); i++)
validcomp.insert(i);
int j = ;
while(!validcomp.empty()) {
for(int pos : validcomp) {
if(vs[pos][j] != vs[pos - ][j])
edges.insert(make_pair(vs[pos - ][j], vs[pos][j]));
else
temp.insert(pos);
}
unordered_set<int> ().swap(validcomp);
validcomp.swap(temp);
j++;
}
return edges;
} //返回所有节点的入度,存入degree里
unordered_map<char, int> getDegree(unordered_multimap<char, char> &edges) {
unordered_map<char, int> degree;
for(char c = 'a'; c <= 'z'; c++) {
auto range = edges.equal_range(c);
auto pos = range.first;
while(pos != range.second) {
//指出节点未出现过,则设0,否则跳过;指入节点未出现过,则设1,否则++。
if(degree.find(pos->first) == degree.end())
degree[pos->first] = ;
if(degree.find(pos->second) != degree.end())
degree[pos->second]++;
else
degree[pos->second] = ;
pos++;
}
}
return degree;
} //进行BFS,用最朴素的方法,复杂度为O(N^2),用这个方法找到符合题目要求的顺序,如果能遍历完全所有节点,则return这个顺序;否则,return ""
bool bfs(string &str, unordered_map<char, int> degree, unordered_multimap<char, char> &edges) {
bool visited[];
memset(visited, , );
for(int i = ; i < degree.size(); i++) {
for(auto m : degree)
//入度为0则排入,然后更新入度hash表
if(!visited[int(m.first - 'a')] && m.second == ) {
visited[int(m.first - 'a')] = true;
str += m.first;
auto range = edges.equal_range(m.first);
auto pos = range.first;
while(pos != range.second) {
degree[pos->second]--;
pos++;
}
break;
}
}
//有环,则return ""
for(auto m : degree)
if(m.second != )
return false;
return true;
}
//主函数
string validOrder(vector<string> vs) {
//string数组映射到图edges上
unordered_multimap<char, char> edges = mapping(vs);
//返回所有节点的入度,存入degree;如果无效,则return "";
unordered_map<char, int> degree = getDegree(edges);
//进行BFS,找到合适的顺序,优先排入入度为0的点
string str = "";
bool valid = bfs(str, degree, edges);
return valid ? str : "";
}

其中,BFS过程,即函数bfs复杂度为O(N^2),N为节点个数,有改进的空间;可以优化为O(E),E为边的个数

//优化BFS
bool bfs(string &str, unordered_map<char, int> degree, unordered_multimap<char, char> &edges) {
queue<char> myq, temp;
for(auto m : degree)
if(m.second == )
myq.push(m.first);
while(!myq.empty()) {
while(!myq.empty()) {
char c = myq.front();
str += c;
myq.pop();
auto range = edges.equal_range(c);
auto pos = range.first;
while(pos != range.second) {
degree[pos->second]--;
if(degree[pos->second] == )
temp.push(pos->second);
pos++;
}
}
queue<char> ().swap(myq);
myq.swap(temp);
}
//有环,则return ""
for(auto m : degree)
if(m.second != )
return false;
return true;
}

[Locked] Alien Dictionary的更多相关文章

  1. 【Leetcode_easy】953. Verifying an Alien Dictionary

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

  2. Verifying an Alien Dictionary

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

  3. [LeetCode] Alien Dictionary 另类字典

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

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

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

  5. Alien Dictionary

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

  6. LeetCode Alien Dictionary

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

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

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

  8. 269. Alien Dictionary

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

  9. [Swift]LeetCode269. 外星人词典 $ Alien Dictionary

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

随机推荐

  1. 关于一点coding.net与git配合在AndroidStudio/Idea上的使用笔记个的

    编写程序的我们经常需要对我们写的代码做版本控制,或者分支管理,具备类似功能的软件很多,诸如SVN,Git,CVS等等!但配置版本控制服务器(SVN server etc.)是繁琐的并且需要一定的成本! ...

  2. 详解SQL Server 2005 Express下的事件探查器

    安装Visual Studio 2008会有附带的SQL Server 2005 Express版 我们开发一般都用那个都不单独安装SQL Server的 大家都知道express版的sql是没有 事 ...

  3. UTF-8和GBK有什么区别?

    字符均使用双字节来表示,只不过为区分中文,将其最高位都定成1. 至于UTF-8编码则是用以解决国际上字符的一种多字节编码,它对英文使用8位(即一个字节),中文使用24位(三个字节)来编码.对于英文字符 ...

  4. javascript基础学习(八)

    javascript之日期对象 学习要点: 日期对象 将日期对象转换为字符串 将日期对象中的日期和时间转换为字符串 日期对象中的日期 日期对象中的时间 设置日期对象中的日期 设置日期对象中的时间 与毫 ...

  5. SGU 174.wall

    题意: 判断给出的线段是否组成了多边形. Solution: 简单题,并查集+hash 这里用map实现 code #include <iostream> #include <cst ...

  6. Meta元素可视区

    一.网页手机wap2.0网页的head里加入下面这条元标签,在iPhone的浏览器中页面将以原始大小显示,并不允许缩放. <meta name="viewport" cont ...

  7. Cookie的基本使用

    1, 如何创建cookie <?php //创建cookie信息 //这个函数用于保存cookie //第一个参数,表示cookie一个key,第二个表示val,第三个表示cookie值,在客户 ...

  8. node应用通过multer模块实现文件上传

    multer用于处理文件上传的nodejs中间件,主要跟express框架搭配使用,只支持表单MIME编码为multipart/form-data类型的数据请求. 如果要处理其他编码的表单数据可以通过 ...

  9. php流行笔试题及答案

    1.在PHP中,当前脚本的名称(不包括路径和查询字符串)记录在预定义变量(1)中:而链接到当前页面的URL记录在预定义变量(2)中. 答:echo $_SERVER['PHP_SELF']; echo ...

  10. Python 的“+”和append在添加字符串时候的区别

    对于一个空的Python列表,往后添加内容有很多种,其中两种一个是用“+”直接添加内容,另外一种是Listname.append(x)来添加内容 其中,如果处理字符串 在使用“+”的时候,会将字符串拆 ...