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,

  1. [
  2. "wrt",
  3. "wrf",
  4. "er",
  5. "ett",
  6. "rftt"
  7. ]

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.

Solution:

  1. public class Solution {
  2. public String alienOrder(String[] words) {
  3. if (words == null || words.length == 0)
  4. return null;
  5. if (words.length == 1) {
  6. return words[0];
  7. }
  8. Map<Character, List<Character>> adjList = new HashMap<Character, List<Character>>();
  9. for (int i = 0; i < words.length - 1; i++) {
  10. String w1 = words[i], w2 = words[i + 1];
  11. int n1 = w1.length(), n2 = w2.length();
  12. boolean found = false;
  13. for (int j = 0; j < Math.max(w1.length(), w2.length()); j++) {
  14. Character c1 = j < n1 ? w1.charAt(j) : null, c2 = j < n2 ? w2.charAt(j) : null;
  15. if (c1 != null && !adjList.containsKey(c1)) {
  16. adjList.put(c1, new ArrayList<Character>());
  17. }
  18. if (c2 != null && !adjList.containsKey(c2)) {
  19. adjList.put(c2, new ArrayList<Character>());
  20. }
  21. if (c1 != null && c2 != null && c1 != c2 && !found) {
  22. adjList.get(c1).add(c2);
  23. found = true;
  24. }
  25. }
  26. }
  27. Set<Character> visited = new HashSet<>();
  28. Set<Character> loop = new HashSet<>();
  29. Stack<Character> stack = new Stack<Character>();
  30. for (Character key : adjList.keySet()) {
  31. if (!visited.contains(key)) {
  32. if (!topologicalSort(adjList, key, visited, loop, stack)) {
  33. return "";
  34. }
  35. }
  36. }
  37. StringBuilder sb = new StringBuilder();
  38. while (!stack.isEmpty()) {
  39. sb.append(stack.pop());
  40. }
  41. return sb.toString();
  42. }
  43. boolean topologicalSort(Map<Character, List<Character>> adjList, char u, Set<Character> visited, Set<Character> loop, Stack<Character> stack) {
  44. visited.add(u);
  45. loop.add(u);
  46. if (adjList.containsKey(u)) {
  47. for (int i = 0; i < adjList.get(u).size(); i++) {
  48. char v = adjList.get(u).get(i);
  49. if (loop.contains(v))
  50. return false;
  51. if (!visited.contains(v)) {
  52. if (!topologicalSort(adjList, v, visited, loop, stack)) {
  53. return false;
  54. }
  55. }
  56. }
  57. }
  58. loop.remove(u);
  59. stack.push(u);
  60. return true;
  61. }
  62. }