[leetCode]Alien Dictionary

挺经典的拓扑排序,注意的就是最后判断是否合法的判据是所有入度都为0

public class Solution {
    public String alienOrder(String[] words) {
        HashMap<Character, Set<Character>> map = new HashMap<Character, Set<Character>>();
        HashMap<Character, Integer> in_degree = new HashMap<Character, Integer>();
        for (String word : words) {
            for (int i = 0; i < word.length(); i++) {
                map.put(word.charAt(i), new HashSet<Character>());
                in_degree.put(word.charAt(i), 0);
            }
        }
        for (int i = 0; i < words.length - 1; i++) {
            String first = words[i];
            String second = words[i + 1];
            for (int j = 0; j < Math.min(first.length(), second.length()); j++) {
                if (first.charAt(j) != second.charAt(j)) {
                    if (!map.get(first.charAt(j)).contains(second.charAt(j))) {
                        in_degree.put(second.charAt(j), in_degree.get(second.charAt(j)) + 1);
                        map.get(first.charAt(j)).add(second.charAt(j));
                    }
                    break;
                }
            }
        }
        Queue<Character> queue = new LinkedList<Character>();
        Iterator<Character> it = in_degree.keySet().iterator();
        while (it.hasNext()) {
            char tmp = it.next();
            if (in_degree.get(tmp) == 0) {
                queue.offer(tmp);
            }
        }
        String result = "";
        while (!queue.isEmpty()) {
            char tmp = queue.poll();
            result = result + tmp;
            Set<Character> set = map.get(tmp);
            for (char ch : set) {
                int id = in_degree.get(ch);
                id -= 1;
                in_degree.put(ch, id);
                if (id == 0) {
                    queue.offer(ch);
                }
            }
        }
        it = in_degree.keySet().iterator();
        while (it.hasNext()) {
            if (in_degree.get(it.next()) != 0) {
                return "";
            }
        }
        return result;
    }
}

 

posted @ 2015-11-26 14:43  Weizheng_Love_Coding  阅读(125)  评论(0)    收藏  举报