LeetCode "Alien Dictionary"

Another topological sorting problem. Note: the DFS one is like a 'post-order' traversal.

class Solution 
{
    unordered_map<char, unordered_set<char>> g;
    unordered_set<char> visited;
    unordered_set<char> rec;
    
public:
    
    bool dfs(string& order, char n) 
    {
        if (rec.count(n)) return false;
        if (visited.count(n)) return true;
    
        visited.insert(n);
        rec.insert(n);
    
        for (auto c : g[n])
            if (!dfs(order, c)) return false;
    
        rec.erase(n);
        order += n;
    
        return true;
    }

    string topsort(unordered_map<char, unordered_set<char>>& g) 
    {
        string order;
    
        for (auto kv : g) 
            if (!dfs(order, kv.first))
                return "";
    
        std::reverse(order.begin(), order.end());
        return order;
    }
    
    string alienOrder(vector<string>& words) 
    {
        if (words.size() == 1) return words.front();
    
        for (int i = 1; i < words.size(); i++) 
        {
            string t1 = words[i - 1];
            string t2 = words[i];           
        
            bool found = false;
            for (int j = 0; j < max(t1.length(), t2.length()); j++) 
            {
                if (j < t1.length() && g.count(t1[j]) == 0)
                    g[t1[j]] = unordered_set<char>();
                if (j < t2.length() && g.count(t2[j]) == 0)
                    g[t2[j]] = unordered_set<char>();
                if (j < t1.length() && j < t2.length() && t1[j] != t2[j] && !found) 
                {
                    g[t1[j]].insert(t2[j]);
                    found = true;
                }
            }
        }
    
        return topsort(g);
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4757112.html