23. Alien Dictionary

Link to the problem

Description

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.

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.

Example

Given the following words in dictionary,

["wrt", "wrf", "er", "ett", "rftt"]
The correct order is: "wertf".

Given the following words in dictionary,
["z", "x"]
The correct order is: "zx".

Given the following words in dictionary,
["z", "x", "z"]
The order is invalid, so return "".

Idea

First derive a graph, then run a topological sorting.

Solution

class Solution {
private:
    bool dfs(char v, unordered_map > &graph,
            string &topological_order, unordered_set &visited,
            unordered_set &finished) {
        if (finished.find(v) != finished.end()) return true;
        if (visited.find(v) != visited.end()) return false;
        visited.insert(v);
        for (char nbr : graph[v]) {
            if (!dfs(nbr, graph, topological_order, visited, finished)) return false;
        }
        finished.insert(v);
        topological_order += v;
        return true;
    }
public:
    string alienOrder(vector& words) {
        unordered_map > graph;
        unordered_set alphabet;
        for (auto &word : words) {
            for (char c : word) alphabet.insert(c);
        }
        int n = words.size();
        for (int i = 0; i < n - 1; ++i) {
            string small = words[i], large = words[i + 1];
            int first_diff = 0;
            while (first_diff < large.size() && first_diff < small.size()) {
                if (small[first_diff] != large[first_diff]) {
                    graph[large[first_diff]].push_back(small[first_diff]);
                    break;
                }
                ++first_diff;
            }
        }
        string topological_order;
        unordered_set visited, finished;
        for (char c : alphabet) {
            if (!dfs(c, graph, topological_order, visited, finished)) return "";
        }
        return topological_order;
    }
};

117 / 117 test cases passed.
Runtime: 4 ms

你可能感兴趣的:(23. Alien Dictionary)