題目
現有一種使用字母的全新語言,這門語言的字母順序與英語順序不同。
假設,您並不知道其中字母之間的先後順序。但是,會收到詞典中獲得一個 不爲空的 單詞列表。因爲是從詞典中獲得的,所以該單詞列表內的單詞已經 按這門新語言的字母順序進行了排序。
您需要根據這個輸入的列表,還原出此語言中已知的字母順序。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/alien-dictionary
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路
大致思路就是根據字母出現的順序先構造出圖來,
然後進行一下拓撲排序就可以了
構造圖的過程就是遍歷字符串,
找到第i個和第i+1個字符串第一對不同的字母,然後建立一對關係。
建立完圖排一個拓撲序就ok了。
代碼
class Solution {
private:
int cnt;
vector<int> in_degree;
vector<vector<int>> graph;
void init_graph(vector<string>& words) {
for (char c : words[0])
if (in_degree[c - 'a'] == -1) ++cnt,in_degree[c - 'a'] = 0;
for (int i = 0; i < words.size() - 1; i++) {
for (char c : words[i + 1])
if (in_degree[c - 'a'] == -1) ++cnt,in_degree[c - 'a'] = 0;
for (int j = 0; j < words[i].size(); j++) {
char from = words[i][j], to = words[i + 1][j];
if (from == to) continue;
graph[from - 'a'].push_back(to - 'a');
++in_degree[to - 'a'];
break;
}
}
}
string topology_sort() {
string ans = "";
queue<int> q;
for (int i = 0; i < in_degree.size(); i++) {
if (in_degree[i] > 0 || in_degree[i] == -1) continue;
q.push(i);
ans += (i + 'a');
}
while (!q.empty()) {
for (int i = q.size(); i > 0; --i) {
int from = q.front(); q.pop();
for (int to : graph[from]) {
if (in_degree[to] == 1) {
q.push(to);
ans += (to + 'a');
}
--in_degree[to];
}
}
}
return ans.size() == cnt ? ans : "";
}
public:
Solution():cnt (0), in_degree(26, -1), graph(26) {}
string alienOrder(vector<string>& words) {
init_graph(words);
return topology_sort();
}
};
執行用時 :4 ms , 在所有 C++ 提交中擊敗了93.18%的用戶
內存消耗 :9 MB , 在所有 C++ 提交中擊敗了100.00%的用戶