码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 269. Alien Dictionary 外文字典

时间:2018-03-09 10:42:39      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:order by   shm   topsort   leetcode   ref   rac   UI   empty   lang   

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

[LeetCode] 269. Alien Dictionary 外文字典

标签:order by   shm   topsort   leetcode   ref   rac   UI   empty   lang   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!