leetcode269 - Alien Dictionary - hard
作者:互联网
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:
- 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.
class Solution { public: string alienOrder(vector<string>& words) { vector<int> indegree(26); unordered_map<char, unordered_set<char>> graph; for (string word: words){ for (char c : word){ if (graph.count(c)) continue; graph.insert({c, unordered_set<char>()}); } } for (int i=1; i<words.size(); i++){ string first = words[i-1]; string second = words[i]; int l = min(first.size(), second.size()); for (int j=0; j<l; j++){ if (first[j] != second[j]){ char out = first[j]; char in = second[j]; if (graph[out].count(in) == 0){ graph[out].insert(in); indegree[in-'a']++; } break; } if (j == l-1 && first.size() > second.size()) return ""; } } string res = ""; queue<char> q; for (auto elem : graph){ if (indegree[elem.first-'a'] == 0){ q.push(elem.first); } } while (!q.empty()){ char cur = q.front(); q.pop(); res += cur; for (char c : graph[cur]){ indegree[c-'a']--; if (indegree[c-'a'] == 0){ q.push(c); } } } return res.size() == graph.size()? res : ""; } };
标签:leetcode269,return,string,indegree,hard,Alien,words,graph,order 来源: https://www.cnblogs.com/xuningwang/p/13919756.html