LeetCode #269 - Alien Dictionary

本文介绍了一种算法,用于根据字典中的单词顺序推导出一种未知的外星语言的字母排序规则。通过构建字符有向图并进行层序遍历,实现了对外星语言字母顺序的有效推断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Example 1:

Input:

[

  "wrt",

  "wrf",

  "er",

  "ett",

  "rftt"

]

Output: "wertf"

Example 2:

Input:

[

  "z",

  "x"

]

Output: "zx"

Example 3:

Input:

[

  "z",

  "x",

  "z"

Output: "" 

Explanation: The order is invalid, so return "".

Note:

1. You may assume all letters are in lowercase.

2. You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.

3. If the order is invalid, return an empty string.

4. There may be multiple valid order of letters, return any one of them is fine.

利用两个单词的字典序大小,构造字符的有向图,从入度为0的点开始层序遍历,入度越小说明字典序越大。

class Solution {
public:
    string alienOrder(vector<string>& words) {
        vector<int> indegree(26,-1);
        set<char> s;
        for(int i=0;i<words.size();i++)
        {
            for(int j=0;j<words[i].size();j++)
            {
                s.insert(words[i][j]);
                indegree[words[i][j]-'a']=0;
            }
        }
        
        vector<vector<int>> v(26);
        for(int i=1;i<words.size();i++)
        {
            string x=words[i-1];
            string y=words[i];
            for(int j=0;j<min(x.size(),y.size());j++)
            {
                if(x[j]!=y[j])
                {
                    v[x[j]-'a'].push_back(y[j]-'a');
                    indegree[y[j]-'a']++;
                    break;
                }
            }
        }
        
        queue<int> q;
        for(int i=0;i<26;i++) if(indegree[i]==0) q.push(i);
        string result;
        while(!q.empty())
        {
            int i=q.front();
            q.pop();
            result+=(i+'a');
            for(int j=0;j<v[i].size();j++)
            {
                indegree[v[i][j]]--;
                if(indegree[v[i][j]]==0) q.push(v[i][j]);
            }
        }
        if(result.size()!=s.size()) return "";
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值