[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 words from the dictionary, where words 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.

给一个单词字典,里面的单词已经排好序了,根据单词首字母的顺序,跟每个单词内部的顺序没有关系,只有单词和前一个单词相同位置不同字间才有先后顺序。

Java:

public class Solution {
    public String alienOrder(String[] words) {   // Topological sorting - Kahn‘s Algorithm
        if(words == null || words.length == 0) {
            return "";
        }
        Map<Character, Set<Character>> graph = new HashMap<>();
        Set<Character> set = new HashSet<>();
        for (String word : words) {
            for (int i = 0; i < word.length(); i++) {
                set.add(word.charAt(i));
            }
        }

        int[] inDegree = new int[26];
        for (int k = 1; k < words.length; k++) {
            String preStr = words[k - 1];
            String curStr = words[k];
            for (int i = 0; i < Math.min(preStr.length(), curStr.length()); i++) {
                char preChar = preStr.charAt(i);
                char curChar = curStr.charAt(i);
                if (preChar != curChar) {
                    if (!graph.containsKey(preChar)) {
                        graph.put(preChar, new HashSet<Character>());
                    }
                    if (!graph.get(preChar).contains(curChar)) {
                        inDegree[curChar - ‘a‘]++;
                    }
                    graph.get(preChar).add(curChar);
                    break;
                }
            }
        }
        Queue<Character> queue = new LinkedList<>();
        for (int i = 0; i < inDegree.length; i++) {
            if (inDegree[i] == 0) {
                char c = (char)(‘a‘ + i);
                if (set.contains(c)) {
                    queue.offer(c);
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!queue.isEmpty()) {
            char c = queue.poll();
            sb.append(c);
            if (graph.containsKey(c)) {
                for (char l : graph.get(c)) {
                    inDegree[l - ‘a‘]--;
                    if (inDegree[l - ‘a‘] == 0) {
                        queue.offer(l);
                    }
                }
            }
        }
        return sb.length() != set.size() ? "" : sb.toString();
    }
}

Python:BFS

class Solution(object):
    def alienOrder(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        result, zero_in_degree_queue, in_degree, out_degree = [], collections.deque(), {}, {}
        nodes = sets.Set()
        for word in words:
            for c in word:
                nodes.add(c)

        for i in xrange(1, len(words)):
            if len(words[i-1]) > len(words[i]) and                 words[i-1][:len(words[i])] == words[i]:
                    return ""
            self.findEdges(words[i - 1], words[i], in_degree, out_degree)

        for node in nodes:
            if node not in in_degree:
                zero_in_degree_queue.append(node)

        while zero_in_degree_queue:
            precedence = zero_in_degree_queue.popleft()
            result.append(precedence)

            if precedence in out_degree:
                for c in out_degree[precedence]:
                    in_degree[c].discard(precedence)
                    if not in_degree[c]:
                        zero_in_degree_queue.append(c)

                del out_degree[precedence]

        if out_degree:
            return ""

        return "".join(result)

Python:DFS  

class Solution2(object):
    def alienOrder(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        # Find ancestors of each node by DFS.
        nodes, ancestors = sets.Set(), {}
        for i in xrange(len(words)):
            for c in words[i]:
                nodes.add(c)
        for node in nodes:
            ancestors[node] = []
        for i in xrange(1, len(words)):
            if len(words[i-1]) > len(words[i]) and                 words[i-1][:len(words[i])] == words[i]:
                    return ""
            self.findEdges(words[i - 1], words[i], ancestors)

        # Output topological order by DFS.
        result = []
        visited = {}
        for node in nodes:
            if self.topSortDFS(node, node, ancestors, visited, result):
                return ""

        return "".join(result)

    # Construct the graph.
    def findEdges(self, word1, word2, ancestors):
        min_len = min(len(word1), len(word2))
        for i in xrange(min_len):
            if word1[i] != word2[i]:
                ancestors[word2[i]].append(word1[i])
                break

    # Topological sort, return whether there is a cycle.
    def topSortDFS(self, root, node, ancestors, visited, result):
        if node not in visited:
            visited[node] = root
            for ancestor in ancestors[node]:
                if self.topSortDFS(root, ancestor, ancestors, visited, result):
                    return True
            result.append(node)
        elif visited[node] == root:
            # Visited from the same root in the DFS path.
            # So it is cyclic.
            return True
        return False

  

  

  

类似题目:

[LeetCode] 207. Course Schedule 课程安排

[LeetCode] 210. Course Schedule II 课程安排II

原文地址:https://www.cnblogs.com/lightwindy/p/8531872.html

时间: 2024-10-15 17:15:20

[LeetCode] 269. Alien Dictionary 外文字典的相关文章

LeetCode 269: Alien Dictionary

Notes: Lots of places need to be remember: Edge cases: 1. Only one word, still need to be calculated as it represents. 2. All unique chars that not be placed in the result means there are several cycles. It must return empty string. Data Structure: 1

269. Alien Dictionary

本质上就是topological sort. 1. 统计所有的点 对于每一个string,把所有的字母都加入indegree 2. 构建图,统计indegree 对于没连续的一组str,找到第一个不同的字母,把后一个加入前一个字母的neighbor,并且给后一个字母indegree+1. 需要注意的是,如果要检查后一个字母是不是已经在第一个字母的neighbor,如果不是再做后续操作 3. 遍历图 注意可能没有邻节点 4. 检查是不是所有点都访问到了,返回结果 1 public String a

leetcode 953. Verifying an Alien Dictionary &amp; 949. Largest Time for Given Digits &amp; 948. Bag of Tokens

leetcode 953. Verifying an Alien Dictionary class Solution { public boolean isAlienSorted(String[] words, String order) { int[] o = new int[26]; for (int i = 0; i < order.length(); ++i) { o[order.charAt(i) - 'a'] = i; } for (int i = 0; i < words.len

[Locked] Alien Dictionary

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 lexicographically by the rules of this new lang

Dictionary(字典)

Dictionary(字典) 字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的.可哈希表示key必须是不可变类型,如:数字.字符串.元组. 字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型.列表是有序的对象结合,字典是无序的对象集合.两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取. 创

Leetcode: Alien Dictionary &amp;&amp; Summary: Topological Sort

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 lexicographically by the rules of this new language. Derive the

[LeetCode] Alien Dictionary

Well, this problem is not that easy. First you may need some clarifications about the problem itself. If you do, you may refer to this link for a nice example which illustrates the purpose of this problem. Moreover, you need to understand graph repre

Dictionary Learning(字典学习、稀疏表示以及其他)

第一部分 字典学习以及稀疏表示的概要 字典学习(Dictionary Learning)和稀疏表示(Sparse Representation)在学术界的正式称谓应该是稀疏字典学习(Sparse Dictionary Learning).该算法理论包含两个阶段:字典构建阶段(Dictionary Generate)和利用字典(稀疏的)表示样本阶段(Sparse coding with a precomputed dictionary).这两个阶段(如下图)的每个阶段都有许多不同算法可供选择,每种

uva 1519 - Dictionary Size(字典树)

题目链接:uva 1519 - Dictionary Size 题目大意:给出n个字符串组成的字典,现在要添加新的单词,从已有单词中选出非空前缀和非空后缀,组成新单词.问说能组成多少个单词. 解题思路:建立一棵前缀树和一棵后缀树,有多少节点即为有多少个前缀,扣除中间的部分即可加上长度为1的字符串即可. #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const