跳转至

火星词典⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    string alienOrder(vector<string>& words) {
        vector<int> inDegree(26, -1);
        for (const string& word : words) {
            for (const char& ch : word)
                inDegree[ch - 'a'] = 0;
        }

        vector<vector<int>> edges(26);
        for (int i = 0; i < words.size() - 1; i++) {
            string currentWord = words[i], nextWord = words[i + 1];
            int len = min(currentWord.length(), nextWord.length());
            int j = 0;
            for (j = 0; j < len; j++) {
                if (currentWord[j] != nextWord[j]) {
                    edges[currentWord[j] - 'a'].push_back(nextWord[j] - 'a');
                    inDegree[nextWord[j] - 'a']++;
                    break;
                }
            }
            if (j < currentWord.length() && j == nextWord.length())
                return "";
        }

        queue<int> que;
        int count = 0;
        for (int i = 0; i < 26; i++) {
            if (inDegree[i] != -1)
                count++;
            if (inDegree[i] == 0)
                que.push(i);
        }

        string res;
        while (!que.empty()) {
            int current = que.front();
            que.pop();
            res.push_back(static_cast<char>(current + 'a'));
            for (int v : edges[current]) {
                if (--inDegree[v] == 0)
                    que.push(v);
            }
        }

        return res.size() == count ? res : "";
    }
};