每日一题 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;
    }
};
相关推荐
alphaTao10 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习10 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
不知名XL10 小时前
day50 单调栈
数据结构·算法·leetcode
@––––––11 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao12 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
TracyCoder12313 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
望舒51315 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
铉铉这波能秀15 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.15 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
铉铉这波能秀16 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple