每日一题 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;
    }
};
相关推荐
6Hzlia4 小时前
【Hot 100 刷题计划】 LeetCode 118. 杨辉三角 | C++ 动态规划题解
c++·leetcode·动态规划
逆境不可逃6 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
副露のmagic6 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法
副露のmagic6 小时前
字符串章节 leetcode 思路&实现
windows·python·leetcode
XiYang-DING6 小时前
【LeetCode】链表 + 快慢指针找中间 | 2095. 删除链表的中间节点
算法·leetcode·链表
米粒19 小时前
力扣算法刷题 Day 29
算法·leetcode·职场和发展
wfbcg9 小时前
每日算法练习:LeetCode 125. 验证回文串 ✅
算法·leetcode·职场和发展
We་ct9 小时前
LeetCode 295. 数据流的中位数:双堆解法实战解析
开发语言·前端·数据结构·算法·leetcode·typescript·数据流
小辉同志10 小时前
739. 每日温度
c++·算法·leetcode
Via_Neo10 小时前
二进制枚举
数据结构·算法·leetcode