leetcode269. 火星词典

现有一种使用英语字母的火星语言,这门语言的字母顺序与英语顺序不同。

给你一个字符串列表 words ,作为这门语言的词典,words 中的字符串已经 按这门新语言的字母顺序进行了排序 。

请你根据该词典还原出此语言中已知的字母顺序,并 按字母递增顺序 排列。若不存在合法字母顺序,返回 “” 。若存在多种可能的合法字母顺序,返回其中 任意一种 顺序即可。

字符串 s 字典顺序小于 字符串 t 有两种情况:

在第一个不同字母处,如果 s 中的字母在这门外星语言的字母顺序中位于 t 中字母之前,那么 s 的字典顺序小于 t 。
如果前面 min(s.length, t.length) 字母都相同,那么 s.length < t.length 时,s 的字典顺序也小于 t 。

示例 1:

输入:words = [“wrt”,“wrf”,“er”,“ett”,“rftt”]
输出:“wertf”
示例 2:

输入:words = [“z”,“x”]
输出:“zx”
示例 3:

输入:words = [“z”,“x”,“z”]
输出:“”
解释:不存在合法字母顺序,因此返回 “” 。

提示:

1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] 仅由小写英文字母组成

解题思路;
经典拓扑排序,不能有环。代码如下:

class Solution {
public:
    unordered_map<char, vector<char>>edges;
    unordered_map<char, int>indegess;
    bool isfalse = false;
    string alienOrder(vector<string>& words) {
        int n = words.size();
        //1. 给每个字符建立数组
        for (auto word : words) {
            for (auto item : word) {
                if (edges.count(item) == 0) {
                    edges[item] = vector<char>();
                }
            }
        }
        // 2. 添加边
        for (int i = 0; i < n - 1 && !isfalse; ++i) {
            addedges(words[i], words[i + 1]);
        } 
        if (isfalse) return "";
        //找到入度为0的点BFS
        queue<char>q;
        for (auto item : edges) {
            if (indegess.count(item.first) == 0) q.push(item.first);
        }
        string res;
        while (!q.empty()) {
            char cur = q.front();
            q.pop();
            for (auto item : edges[cur]) {
                if (indegess[item] == 0) return ""; //入度为0说明有环
                else if (indegess[item] == 1) q.push(item);
                indegess[item]--;
            }
            res += cur;
        }
        if (res.size() != edges.size()) return "";
        return res;

    }
    void addedges(const string& a, const string& b) {
        int lena = a.size();
        int lenb = b.size();
        int len = min(lena, lenb);
        int index = 0;
        while (index < len) {
            if (a[index] != b[index]) {
                edges[a[index]].emplace_back(b[index]);
                indegess[b[index]]++;
                break;
            }
            index++;
        }
        if (index == len && lena > lenb) isfalse = true;
        return;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值