每日一题 LCR 114. 火星词典

LCR 114. 火星词典

使用拓扑排序就可以,有一个实例需要考虑特殊情况

cpp 复制代码
class Solution {
public:
    string alienOrder(vector<string>& words) {
        unordered_map<char,unordered_set<char>> graph;
        unordered_map<char,int>  inorder;
        int n = words.size();

        for(int i=0;i<n;++i){
                for(int k=0;k<words[i].size();++k){
                    inorder[words[i][k]] = 0;
                }
        }

        bool special = true;
        //建图
        for(int i=0;i<n;++i){
            for(int j=i+1;j<n;++j){
                special = true;
                for(int k=0;k<min(words[i].size(),words[j].size());++k){
                    
                    if(words[i][k] != words[j][k]){
                        if(!graph[words[i][k]].count(words[j][k])){
                            graph[words[i][k]].insert(words[j][k]);
                        
                            inorder[words[j][k]]++;
                        }
                        special = false;
                        break;

                    }
                }
                if(special && words[i].size() > words[j].size()){
                    return "";
                }
            }
        }


        queue<char> que;
        for(auto [u,v]:inorder){
            if(v == 0){
                que.push(u);
            }
        }
        string ret = "";
        while(!que.empty()){
            auto t = que.front();
            que.pop();
            ret = ret + t;
            for(auto e : graph[t]){
                inorder[e]--;
                if(inorder[e] == 0){
                    que.push(e);
                }
            }
        }
        if(ret.size() != inorder.size()){
            return "";
        }
        return ret;
    }
};
相关推荐
YLCHUP1 小时前
【模拟&STL】题解:AT_abc203_e [ABC203E] White Pawn_基础算法_数据结构_STL模板库_AtcoderABC_C++算法竞赛
数据结构·c++·算法·leetcode·动态规划·哈希算法·近邻算法
(●—●)橘子……1 小时前
力扣 第525场周赛 练习理解
数据结构·python·学习·算法·leetcode
wenyq72 小时前
LeetCode 152. Maximum Product Subarray
java·算法·leetcode
文丑颜不良啊2 小时前
LeetCode1181~1200题目解析
java·leetcode
海绵宝宝转agent3 小时前
Leetcode100+面经
java·笔记·学习·算法·leetcode·深度优先
Shaoshing3 小时前
LeetCode100 283.移动零
java·数据结构·算法·leetcode
文丑颜不良啊3 小时前
LeetCode1201~1220题目解析
java·leetcode
文丑颜不良啊3 小时前
LeetCode1161~1180题目解析
java·leetcode
一去不复返的通信er13 小时前
贪心算法-合并区间(LeetCode 56)
算法·leetcode·贪心算法
INGNIGHT17 小时前
91 · 最小调整代价(序列dp)
数据结构·算法·leetcode