每日一题 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;
    }
};
相关推荐
Allen Wurlitzer4 小时前
算法刷题记录——LeetCode篇(1.9) [第81~90题](持续更新)
算法·leetcode·职场和发展
阳洞洞4 小时前
leetcode 377. Combination Sum IV
算法·leetcode·动态规划·完全背包问题
想跑步的小弱鸡8 小时前
Leetcode hot 100(last day)
算法·leetcode·哈希算法
龙俊杰的读书笔记13 小时前
[leetcode] 面试经典 150 题——篇9:二叉树(番外:二叉树的遍历方式)
数据结构·算法·leetcode·面试
Swift社区14 小时前
从表格到序列:Swift 如何优雅地解 LeetCode 251 展开二维向量
开发语言·leetcode·swift
飞川撸码18 小时前
【LeetCode 热题100】73:矩阵置零(详细解析)(Go语言版)
leetcode·矩阵·golang
小美爱刷题20 小时前
力扣DAY40-45 | 热100 | 二叉树:直径、层次遍历、有序数组->二叉搜索树、验证二叉搜索树、二叉搜索树中第K小的元素、右视图
数据结构·算法·leetcode
熬夜造bug21 小时前
LeetCode Hot100 刷题笔记(2)—— 子串、普通数组、矩阵
笔记·leetcode·矩阵
lvchaoq1 天前
图解力扣回溯及剪枝问题的模板应用
leetcode·深度优先·剪枝·回溯·递归
Swift社区1 天前
LeetCode 252 会议室题全解析:Swift 实现 + 场景还原
算法·leetcode·swift