• 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
  • 相关阅读:
    实验一
    BZOJ 2564
    P4557 [JSOI2018]战争
    移动自动化-Mac-IOS-appium环境搭建
    Node安装mac版本
    删除N天前文件和空文件
    Python之jsonpath模块
    性能学习
    参数化
    查找测试用例
  • 原文地址:https://www.cnblogs.com/tonix/p/4757112.html
Copyright © 2020-2023  润新知