zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    最长递增长度 (最长上升子序列)
    完全背包问题
    vue中使用el-tabs组件遇到的问题
    ORACLE中排序的时候空值处理
    ORA-01089数据库无法正常关闭
    Oracle中的LPAD和RPAD的使用
    Oracle中Translate函数的使用
    通过对照表快速建view
    Oracle数据库create or replace
    打字网站
  • 原文地址:https://www.cnblogs.com/tonix/p/4757112.html
Copyright © 2011-2022 走看看