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:
Given the following words in dictionary,
[ "wrt", "wrf", "er", "ett", "rftt" ]
The correct order is: "wertf"
.
Example 2:
Given the following words in dictionary,
[ "z", "x" ]
The correct order is: "zx"
.
Example 3:
Given the following words in dictionary,
[ "z", "x", "z" ]
The order is invalid, so return ""
.
Note:
- You may assume all letters are in lowercase.
- You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
- If the order is invalid, return an empty string.
- There may be multiple valid order of letters, return any one of them is fine.
这样构建一个图结构。
使用hash table 记录指向当前char的边的个数,即indegree;使用另一个hash table记录当前插入 能指向的char的set集合,这样就表示出了一张图。
对每一个节点进行遍历,找到入度为0的点,将其加入order 序列, 然后将其指向的char的set集合中所有char对应的入度都-1,注意将当前的char的indegree也-1得到-1避免重复访问。
细节问题:
1 构建图的时候,要注意判断重复边,如果一个char的set集合中已经包含了当前char,那么不用再更新其indegree
2 auto i:indegree的时候,通过i并不能更新indegree中的数值
3 要判断没有操作过所有char的时候如果找不到indegree为0的点了,说明不能找到符合要求的order,这个时候要特判一下,返回“”
4 不能在words.size() == 1的时候返回“”,因为"wnlb" 应该返回任意组合。
代码如下:
class Solution {
public:
string alienOrder(vector<string>& words) {
string res;
unordered_map<char, int> indegree;
unordered_map<char, unordered_set<char>> graph;
for (auto s:words)
for (auto ch:s)
indegree[ch] = 0;//初始化indegree
for (int i = 1; i < words.size(); i++) {//构建图和计算正确的indegree值
string word1 = words[i-1];
string word2 = words[i];
int j = 0;
while (j < word1.size() && j < word2.size()) {
if (word1[j] != word2[j]) {
if (graph[word1[j]].find(word2[j]) == graph[word1[j]].end()){//找不到的时候才更新indegree
indegree[word2[j]]++;
graph[word1[j]].insert(word2[j]);
}
break;//break很重要,因为只有第一对是有先后关系的
}
j++;
}
}
for (int i = 0; i < indegree.size(); i++) {//要对所有的char进行一次操作
char ch = ' ';
for (auto in:indegree) {
if (in.second == 0) {
ch = in.first;
break;
}
}
if (ch == ' ') return ""; // 判断不能组成正确顺序的条件
res += ch;
indegree[ch]--;
for (auto g:graph[ch]) indegree[g]--;
}
// while(1) {
// char ch = ' ';
// for (auto in:indegree) {//不能通过in.second--来改变indegree中对应值
// if (in.second == 0) {
// ch = in.first;
// break;
// }
// }
// if (ch == ' ') {//这样不能区分到底是所有char都操作了一遍,还是不能的出正确的order
// break;
// }
// res += ch;
// indegree[ch]--;
// for (auto g:graph[ch]) indegree[g]--;
// }
return res;
}
};