Alien Dictionary Leetcode
未完待续
public class Solution { public String alienOrder(String[] words) { HashMap<Character, ArrayList<Character>> hm = new HashMap<>(); HashMap<Character, Integer> degree = new HashMap<>(); for (int i = 0; i < words.length - 1; i++) { char[] first = words[i].toCharArray(); char[] second = words[i + 1].toCharArray(); int length = Math.min(first.length, second.length); for (int j = 0; j < length; j++) { if (first[j] != second[j]) { if (!hm.containsKey(first[j])) { hm.put(first[j], new ArrayList<>()); } hm.get(first[j]).add(second[j]); if (!hm.containsKey(second[j])) { hm.put(second[j], new ArrayList<>()); } if (!degree.containsKey(first[j])) { degree.put(first[j], 0); } if (!degree.containsKey(second[j])) { degree.put(second[j], 1); } else { degree.put(second[j], degree.get(second[j]) + 1); } break; } else { if (!hm.containsKey(first[j])) { hm.put(first[j], new ArrayList<>()); } if (!degree.containsKey(first[j])) { degree.put(first[j], 0); } } } } Queue<Character> q = new LinkedList<>(); for (Character c : degree.keySet()) { if (degree.get(c) == 0) { q.offer(c); } } StringBuilder res = new StringBuilder(); while (!q.isEmpty()) { Character c = q.poll(); ArrayList<Character> second = hm.get(c); for (int i = 0; i < second.size(); i++) { degree.put(second.get(i), degree.get(second.get(i)) - 1); if (degree.get(second.get(i)) == 0) { q.offer(second.get(i)); } } res.append(c); } if (res.length() != degree.size()) { return ""; } return res.toString(); } }