每日一题 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;
    }
};
相关推荐
All for pursuit.4 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
CoderYanger8 小时前
A.每日一题:1614. 括号的最大嵌套深度
java·程序人生·算法·leetcode·面试·学习方法
Xin7709 小时前
LeetCode 230. 二叉搜索树中第 K 小的元素(迭代中序遍历 + 栈)
leetcode
Navigator_Z10 小时前
LeetCode //C - 1283. Find the Smallest Divisor Given a Threshold
c语言·算法·leetcode
我不会起名字32211 小时前
二叉树的遍历与二叉搜索树:把递归、迭代、还原树一次讲透
数据结构·leetcode·二叉树·二叉搜索树
yi01111 小时前
Leetcode 49 用 “身份证‘‘巧解
人工智能·笔记·python·算法·leetcode·哈希表
yi01112 小时前
DAY22: LeetCode 733:图像渲染——从二维网格开始理解 DFS 和 BFS
数据结构·笔记·python·算法·leetcode·深度优先·宽度优先
Pniubi12 小时前
力扣41缺失的第一个正数(哈希表法)
算法·leetcode·职场和发展
Nil20813 小时前
leetcode 70爬楼梯
算法·leetcode·动态规划
longlongzihan15 小时前
LeetCode 189. 轮转数组:从直观模拟到最优原地算法
c++·算法·leetcode