LeetCode 269. Alien Dictionary(外星人字典)

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

原题网址:https://leetcode.com/problems/alien-dictionary/

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 words from the dictionary, wherewords are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

For example,
Given the following words in dictionary,

[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]

The correct order is: "wertf".

Note:

  1. You may assume all letters are in lowercase.
  2. If the order is invalid, return an empty string.
  3. There may be multiple valid order of letters, return any one of them is fine.
思路:

(1)如何生成图?前后两个单词的逐个字母检查,这个方法实现起来最简单。

(2)如何生成字母表?可以用深度优先搜索或者拓扑排序。


方法一:图的深度优先搜索。深度优先的关键点在于如何检查环路,使用visited=0/1/2而不是布尔类型可以解决,即visited=0表示未访问UNVISITED,1表示访问中VISITING,2表示已访问VISITED。另外,深度优先搜索的话,graph用入边来表示,graph[i][j] = true <=> j->i,这样就容易通过递归方式,先解决所依赖的节点。

public class Solution {
    private void find(boolean[] alphabets, boolean[][] graph, int tail, int[] visited, StringBuilder sb) {
        if (!alphabets[tail] || visited[tail] != 0) return;
        visited[tail] = 1;
        for(int i=0; i<graph[tail].length; i++) {
            if (graph[tail][i] && alphabets[i] && visited[i] == 1) return;
            if (graph[tail][i] && alphabets[i] && visited[i] == 0) find(alphabets, graph, i, visited, sb);
        }
        visited[tail] = 2;
        sb.append((char)(tail+'a'));
    }
    public String alienOrder(String[] words) {
        char[][] ws = new char[words.length][];
        boolean[] alphabets = new boolean[26];
        int letters = 0;
        for(int i=0; i<words.length; i++) {
            ws[i] = words[i].toCharArray();
            for(int j=0; j<ws[i].length; j++) {
                if (!alphabets[ws[i][j]-'a']) {
                    alphabets[ws[i][j]-'a'] = true;
                    letters ++;
                }
            }
        }
        boolean[][] graph = new boolean[26][26];
        for(int i=0; i<words.length-1; i++) {
            for(int j=0; j<Math.min(words[i].length(), words[i+1].length()); j++) {
                if (ws[i+1][j] != ws[i][j]) {
                    graph[ws[i+1][j]-'a'][ws[i][j]-'a'] = true;
                    break;
                }
            }
        }
        int[] visited = new int[26];
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<alphabets.length; i++) {
            if (!alphabets[i] || visited[i]!=0) continue;
            find(alphabets, graph, i, visited, sb);
        }
        // System.out.println(sb.toString());
        if (sb.length() == letters) return sb.toString(); else return "";
    }
}


方法二:拓扑排序。需要检查判断无法再继续生成字母表的情况(环路),如果使用出边来表示graph,即graph[i][j] = true <=> i-->j,则需要另外再辅助入度的变量indegrees。

public class Solution {
    public String alienOrder(String[] words) {
        boolean[][] graph = new boolean[26][26];
        int[] indegrees = new int[26];
        boolean[] alphabets = new boolean[26];
        int alphabetsCount = 0;
        char[] word =new char[0];
        for(int i=0; i<words.length; i++) {
            char[] prev = word;
            word = words[i].toCharArray();
            for(int j=0; j<word.length; j++) {
                if (!alphabets[word[j]-'a']) {
                    alphabets[word[j]-'a'] = true;
                    alphabetsCount ++;
                }
            }
            for(int j=0; j<Math.min(prev.length, word.length); j++) {
                if (prev[j] != word[j]) {
                    if (!graph[prev[j]-'a'][word[j]-'a']) {
                        graph[prev[j]-'a'][word[j]-'a'] = true;
                        indegrees[word[j]-'a'] ++;
                    }
                    break;
                }
            }
        }
        char[] result = new char[alphabetsCount];
        int pos = 0;
        do {
            boolean changed = false;
            for(int i=0; i<alphabets.length; i++) {
                if (alphabets[i]) {
                    if (indegrees[i] == 0) {
                        result[pos++] = (char)(i+'a');
                        changed = true;
                        for(int j=0; j<graph[i].length; j++) {
                            if (graph[i][j]) {
                                indegrees[j] --;
                            }
                        }
                        alphabets[i] = false;
                    }
                }
            }
            if (!changed) break;
        } while (pos < result.length);
        return pos == result.length ? new String(result) : "";
    }
}


Leetcode 269. Alien Dictionary 方法1: topological sort + bfs。这道题和210题思路一模一样,都是graph题,拓扑排序问题。一般来说拓扑排序问题可以分为以下三个步骤: graph题里面还有一个很重要的点就是detect circle,这道题目关于这个点我还没搞得很清楚,复盘的时候记得搞清楚。这边我建议仔细阅读lc官方解答1,这个解答吧这个问题解释地非常清楚。 class Solution { public String alienOrder(String[] words) { Map&l. 阅读详情

相关推荐

Leetcode 953:验证外星语词典(超详细的解法!!!)

某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。 给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。 示例 1: 输入:words = ["hello","leetcode"], order = "hlabcdefgijkmnopq...

coordinate的博客 3849

[Leetcode] Alien Dictionary

这一题的关键词其实只有一个:拓扑排序。 整个流程其实就是很简单的:建图+排序。 如果建图过程里面发现了有向环,就表示order invalid,上图第三个例子就是一个有向环,z -&gt; x -&gt; z。否则建图之后答案就是一个拓扑排序的结果。可以有bfs和dfs两种。 先说如何建图: 1. 这是一个特殊的alphabetical排序。用example 1来说就是"wrt" &gt; ...

chaochen1407的专栏 868

leetcode苹果-verifying-an-alien-dictionary:验证外星人词典

leetcode 苹果验证外星人词典 在外星语言中,令人惊讶的是,它们也使用英文小写字母,但顺序可能不同。 字母表的顺序是一些小写字母的排列。 给定一个用外星语言书写的单词序列和字母表的顺序,当且仅当给定的单词在该外星语言中按字典顺序排序时才返回 true。 Example 1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence t

Leetcode269. Alien Dictionary

同时,在计入度的时候,要在建图完了再计,遍历数组的时候只需要计一下哪些字符出现过就可以了,原因是,怕平行边出现,会把入度计的更多。比较BFS和DFS我们可以发现, DFS的优势在于不需要记录入度,并且逻辑相对也更简单,更好写。如果发现排序的结果的长度不够全部的字符的个数,则直接返回空串,否则返回排序结果。的字典序的先后,是按照字符依次比较,如果发现了第一个不同的字符,例如在下标为。是按照字典序排序的,但是其字典序是另外定义的,并不一定是。的情形,此时任何顺序都是合法的,但是要注意去重。

数学、算法爱好者的博客 739

Leetcode 269. Alien Dictionary(python)

Leetcode 269. Alien Dictionary题目解法:拓扑排序 题目 解法:拓扑排序 这道题的解法leetcode官方写的非常好,也非常有助于理解拓扑排序,建议仔仔细细地看他的官方解析 class Solution: def alienOrder(self, words: List[str]) -> str: # create adject matrx of the graph adj_list = collections.defaultdic

qq_37821701的博客 2659

LeetCode(269) Alien Dictionary (Java)

题目如下: 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 words from the dictionary, where words are sorted lexicog

BUILD 4573

[Swift]LeetCode269. 外星人词典 $ Alien Dictionary

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30762087的博客 136

晨哥Leetcode 269. Alien Dictionary

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 lex...

weixin_45588823的博客 199

LeetCode269.火星人词典 ·  alien-dictionary (Hard)

269. 火星人词典 · alien-dictionary 有一种新的使用拉丁字母的外来语言。但是,你不知道字母之间的顺序。你会从词典中收到一个非空的单词列表,其中的单词在这种新语言的规则下按字典顺序排序。请推导出这种语言的字母顺序。 说明: 你可以假设所有的字母都是小写。 如果a是b的前缀且b出现在a之前,那么这个顺序是无效的。 如果顺序是无效的,则返回空字符串。 这里可能有多个有效的字母顺序,返回以正常字典顺序看来最小的。 例1: 输入:["wrt","wrf","er","ett",".

It’s All Uphill From Here 1110

LeetCode Top Interview Questions 269. Alien Dictionary (Java版; Hard)

welcome to my blog LeetCode Top Interview Questions 269. Alien Dictionary (Java版; Hard) 题目描述 There is a new alien language which uses the latin alphabet. However, the order among letters are unknown t...

littlehaes的博客 374

LeetCode 269.火星词典

现有一种使用英语字母的外星文语言,这门语言的字母顺序与英语顺序不同。 给定一个字符串列表 words ,作为这门语言的词典,words 中的字符串已经 按这门新语言的字母顺序进行了排序 。 请你根据该词典还原出此语言中已知的字母顺序,并 按字母递增顺序 排列。若不存在合法字母顺序,返回 "" 。若存在多种可能的合法字母顺序,返回其中 任意一种 顺序即可。 字符串 s 字典顺序小于 字符串 t 有两种情况: 在第一个不同字母处,如果 s 中的字母在这门外星语言的字母顺序中位于 t 中字母之前,那么 s 的字

qq_43708373的博客 610

[leetcode] 269. Alien Dictionary 解题报告

题目链接: https://leetcode.com/problems/alien-dictionary/ 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 words

小榕流光的专栏 7054

[LeetCode269]Alien Dictionary

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 words from the dictionary, where words are sorted lexicographical

MoM 2187

LeetCode269. Alien Dictionary 火星词典

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 lexi...

七月听雪的博客 495

LeetCode Alien Dictionary

原题链接在这里:https://leetcode.com/problems/alien-dictionary/ 题目: There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list ofno...

weixin_30294709的博客 224

leetcode剑指offer II 114. 外星文字典 (构建有向图+有向图的拓扑排序)

有向图生成+拓扑排序

coding_diamond的博客 303

Leetcode之 剑指 Offer II 114. 外星文字典

题目: 现有一种使用英语字母的外星文语言,这门语言的字母顺序与英语顺序不同。 给定一个字符串列表 words ,作为这门语言的词典,words 中的字符串已经 按这门新语言的字母顺序进行了排序 。 请你根据该词典还原出此语言中已知的字母顺序,并 按字母递增顺序 排列。若不存在合法字母顺序,返回 "" 。若存在多种可能的合法字母顺序,返回其中 任意一种 顺序即可。 字符串 s 字典顺序小于 字符串 t 有两种情况: 在第一个不同字母处,如果 s 中的字母在这门外星语言的字母顺序中位于 t 中字母之前

qq_35455503的博客 440

LeetCode剑指 Offer II 114. 外星文字典

剑指 Offer II 114. 外星文字典

weixin_54106682的博客 1033

每日一题-leetcode 验证外星语词典

某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。 给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。 示例 1: 输入:words = [“hello”,“leetcode”], order = “hlabcdefgijkmnopqrstuvwxyz” 输出:true 解释:在该语言的字母表中,‘h’ 位于 ‘l’ 之前,所以单词序列是按字

kangbin825的专栏 337
上一篇: LeetCode 268. Missing Number(缺失数字)
下一篇: LeetCode 270. Closest Binary Search Tree Value(二叉搜索树最接近值查找)
jmspan
博客等级 码龄10年 99粉丝 431原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值