# Topological Sort - Clean Java Solution

• ``````public class Solution {
private class GNode {
char c;
int inD;
Set<GNode> neib;
public GNode(char val) {
c = val;
neib = new HashSet<>();
inD = 0;
}
}
public String alienOrder(String[] words) {
if (words == null || words.length == 0) return "";
Map<Character, GNode> V = new HashMap<>();
for (String word : words) {
for (char c : word.toCharArray()) {
if (!V.containsKey(c)) V.put(c, new GNode(c));
}
}
for (int i = 0; i < words.length - 1; ++i) {
buildGraph(words[i], words[i + 1], V);
}
List<GNode> topoList = topoSort(V);
if (topoList.size() == 0) return "";
StringBuilder res = new StringBuilder();
for (GNode node : topoList) res.append(node.c);
return res.toString();
}
private void buildGraph(String a, String b, Map<Character, GNode> V) {
int i = 0, j = 0;
while (i < a.length() && j < b.length()) {
char p = a.charAt(i), q = b.charAt(j);
if (p != q) {
if (!V.get(p).neib.contains(V.get(q))) {
++V.get(q).inD;
}
break;
}
++i;
++j;
}
}
private List<GNode> topoSort(Map<Character, GNode> V) {
for (GNode node : V.values()) {
}
if (list.size() == 0) return res;
while (list.size() != 0) {
for (GNode node : list) {
for (GNode neib : node.neib) {