2015年9月17日星期四

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.

public class Solution {
    public String alienOrder(String[] words) {
        HashMap<Character, Set<Character>> map = new HashMap<>();
        HashMap<Character, Integer> inDegree = new HashMap<>();
        for (String word : words) {
            for (char c : word.toCharArray()) {
                inDegree.put(c, 0);
            }
        }
        for (int i = 0; i < words.length; i++) {
            String w1 = words[i];
            for (int j = i + 1; j < words.length; j++) {
                String w2 = words[j];
                for (int k = 0; k < w1.length() && k < w2.length(); k++) {
                    char from = w1.charAt(k);
                    char to = w2.charAt(k);
                    if (from == to) continue;
                    Set<Character> tos = map.get(from);
                    if (tos == null) {
                        tos = new HashSet<Character>();
                        map.put(from, tos);
                    }
                    if (!tos.contains(to)) {
                        tos.add(to);
                        inDegree.put(to, inDegree.get(to) + 1);
                    }
                    break;
                }
            }
        }
        LinkedList<Character> queue = new LinkedList<Character>();
        StringBuilder sb = new StringBuilder();
        for (Character key : inDegree.keySet()) {
            if (inDegree.get(key) == 0) {
                queue.add(key);
            }
        }
        while (!queue.isEmpty()) {
            char c = queue.pop();
            sb.append(c);
            if (!map.containsKey(c)) continue;
            for (char to : map.get(c)) {
                inDegree.put(to, inDegree.get(to) - 1);
                if (inDegree.get(to) == 0) {
                    queue.add(to);
                }
            }
        }
        if (sb.length() != inDegree.size()) return "";
        else return sb.toString();
    }
}

没有评论:

发表评论