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: You may assume all letters are in lowercase. If the order is invalid, return an empty string. There may be multiple valid order of letters, return any one of them is fine.
Solution: Topological sort, we need build the graph first and calculate the indegree. The code can be divided to several parts.
public String alienDict(String[] words)
if(words == null || words.length == 0) {
return "";
}
Map<Character, Set<Character>> graph = new HashMap<Character, Set<Character>>();
Map<Character, Integer> indegree = new HashMap<Character, Integer>();
StringBuilder sb = new StringBuilder();
initialize(words, graph, indegree);
buildGraphAndIndegree(words, graph, indegree);
topologicalSort(words, graph, indegree, sb);
return sb.length() == indegree.size() ? sb.toString() : "";
}
public void initialize(String[] words, Map<Character, Set<Character>> graph, Map<Character, Integer> indegree) {
for(int i = 0; i < words.length; i++) {
if(!graph.containsKey(c1)) {
graph.put(c1, new HashSet<Character>());
}
if(!indegree.containsKey(c)) {
indegree.put(c1, 0);
}
}
}
public void buildGraphAndIndegree(String[] words,
Map<Character, Set<Character>> graph,
Map<Character, Integer> indegree) {
for(int i = 0; i < words.length - 1; i++) {
String word1 = words[i];
String word2 = words[i + 1];
for(int j = 0; j < word1.length && j < word2.length; j++) {
char c1 = word1.charAt(j);
char c2 = word2.charAt(j);
if(c1 != c2) {
Set<Character> set = graph.get(c1);
if(!set.contains(c2)) {
set.add(c2);
indegree.put(c2, indegree.get(c2) + 1);
graph.put(c1, set);
}
break;
}
}
}
}
public String topologicalSort(String[] words,
Map<Character, Set<Character>> graph,
Map<Character, Integer> indegree,
StringBuilder sb) {
Queue<Character> queue = new LinkedList<Character>();
for(Character c : indegree) {
if(indegree.get(c) == 0) {
queue.offer(c);
}
}
while(!queue.isEmpty()) {
char tmp = queue.poll();
sb.append(tmp);
for(Character cc : graph.get(tmp)) {
int degree = indegree.get(cc);
if(degree > 0) {
degree--;
indegree.put(cc, degree);
}
else {
queue.offer(cc);
}
}
}
return sb.toString();
}
}