Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. class Solution {
  2. public String alienOrder(String[] words) {
  3.  
  4. int maxLength = getMaxLength(words);
  5. Map<Character, List<Character>> graph = buildGraph(maxLength, words);
  6. List<Character> result = new ArrayList<>();
  7. Set<Character> visited = new HashSet<>();
  8. Set<Character> visiting = new HashSet<>();
  9. for(Character c: graph.keySet()) {
  10. if(!visited.contains(c)) {
  11. if(!topSort(graph, visiting, visited, c, result)) return "";
  12. }
  13. }
  14. StringBuilder sb = new StringBuilder();
  15. for(Character c: result) {
  16. sb.append(c);
  17. }
  18. return sb.toString();
  19. }
  20.  
  21. private int getMaxLength(String[] words) {
  22. Integer n = Integer.MIN_VALUE;
  23. for(String word: words) {
  24. n = Math.max(n, word.length());
  25. }
  26. return n;
  27. }
  28.  
  29. private Map<Character, List<Character>> buildGraph(int maxLength, String[] words) {
  30. Map<Character, List<Character>> map = new HashMap<>();
  31.  
  32. for(int i = 0;i<maxLength;i++) {
  33. Character prev = null;
  34. for(String word: words) {
  35. if(word.length()<=i) break;
  36. Character c = word.charAt(i);
  37. if(prev == null) {
  38. prev = c;
  39. } else {
  40. if(prev != c) {
  41. map.putIfAbsent(prev, new ArrayList<>());
  42. if(!map.get(prev).contains(c)) {
  43. // only add if not contains, check required because of list
  44. map.get(prev).add(c);
  45. }
  46.  
  47. }
  48. prev = c;
  49. }
  50. }
  51. }
  52. return map;
  53. }
  54.  
  55. private boolean topSort(Map<Character, List<Character>> graph, Set<Character> visiting, Set<Character> visited, Character curr, List<Character> result) {
  56.  
  57. if(visiting.contains(curr)) return false;
  58.  
  59. visiting.add(curr);
  60. if(!graph.containsKey(curr)) return true;
  61. for(Character neighbor: graph.get(curr)) {
  62. if(!topSort(graph, visiting, visited, neighbor, result)) return false;
  63. }
  64. visiting.remove(curr);
  65. visited.add(curr);
  66. result.add(curr);
  67. return true;
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement