码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Alien Dictionary"

时间:2015-08-25 14:10:04      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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

LeetCode "Alien Dictionary"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4757112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!