269. Alien Dictionary

Hard
no need to copy questions, you’ll check LeetCode anyway
第一,构图,构造 degree
第二,topological sort

class Solution {
    public String alienOrder(String[] words) {

        StringBuilder res = new StringBuilder();
        Map<Character, Integer> indegree = new HashMap<>();
        Map<Character, HashSet<Character>> graph = new HashMap<>();

        for (String word : words){
            for (char c : word.toCharArray()){
                if (!graph.containsKey(c)){
                    graph.put(c, new HashSet<Character>());
                }
                if (!indegree.containsKey(c)){
                    indegree.put(c, 0);
                }
            }
        }

        for (int i = 0; i < words.length - 1; i++){
            String curt = words[i];
            String next = words[i + 1];
            int lenCurt = curt.length();
            int lenNext = next.length();
            int len = Math.min(lenCurt, lenNext);
            for (int j =  0; j < len; j++){
                char c1 = curt.charAt(j);
                char c2 = next.charAt(j);   
                if (c1 != c2){
                    HashSet<Character> set = graph.get(c1);
                    if (!set.contains(c2)){
                        set.add(c2);
                        indegree.put(c2, indegree.get(c2) + 1);
                    } 
                    break;
                }

            }
        }

        Queue<Character> queue = new LinkedList<>();
        for (Character c : indegree.keySet()){
            if (indegree.get(c) == 0){
                queue.offer(c);
            }
        }

        while (!queue.isEmpty()){
            char c = queue.poll();
            res.append(c);
            for (Character nei : graph.get(c)){
                indegree.put(nei, indegree.get(nei) - 1);
                if (indegree.get(nei) == 0){
                    queue.offer(nei);
                }
            }
        }

        if (res.length() != graph.size()){
            return "";
        }
        return res.toString();
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/5c218196de18
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞