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.
这道题虽然是Hard吧,但其实思路很清晰,没有什么很难的地方。思路捋清楚就好了。大致分为两步:
1. 根据字典中的文字,找出先后顺序。如何找出先后顺序呢?这里我用了一个很弱智的O(N2)的方法,就是遍历所有的字符串p,q,依次对比每一个字符,直到找到第一个不相等的字符,p[idx] 和 q[idx]. 因为p在q的前面,所以p[idx] -> q[idx]。
2. 在找出所有的先后关系之后,我们可以用拓扑排序来求出最后的答案,这里要注意,如果排序出来的字符比words中的字符要少,说明之中存在环。即不能排序。
代码如下:
class Solution {
public:
string alienOrder(vector<string>& words) {
string result;
unordered_set<char> used;
unordered_map<char,unordered_set<char>> map = generate(words,used);
//toplogical sort
unordered_map<char,int> indegree;
queue<char> que;
for (auto cha:used) {
for (auto node:map[cha]) {
indegree[node]++;
}
}
for (auto i:used) {
if (indegree[i] == 0) {
que.push(i);
}
}
//bfs
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
char cur = que.front();
que.pop();
result.push_back(cur);
for (auto j:map[cur]) {
indegree[j]--;
if (indegree[j] == 0)
que.push(j);
}
}
}
if (result.size() != used.size())
result.clear();
return result;
}
private:
unordered_map<char,unordered_set<char>> generate(vector<string> &words,unordered_set<char> &used) {
unordered_map<char,unordered_set<char>> result;
for (int i = 0; i < words.size(); i++) {
string ll = words[i];
for (int k = 0; k < ll.size(); k++)
used.insert(ll[k]);
for (int j = i + 1; j < words.size(); j++) {
string p = words[i];
string q = words[j];
int idx = 0;
while (idx < p.size() && idx < q.size() && p[idx] == q[idx])
idx++;
if (idx < p.size() && idx < q.size())
result[p[idx]].insert(q[idx]);
}
}
return result;
}
};