LeetCode 269: Alien Dictionary
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 269: Alien Dictionary相关的知识,希望对你有一定的参考价值。
Notes: Lots of places need to be remember:
Edge cases:
1. Only one word, still need to be calculated as it represents.
2. All unique chars that not be placed in the result means there are several cycles. It must return empty string.
Data Structure:
1. Better use HashSet in Map. Otherwise, it could be duplicates.
2. Remove keys from map should be outside of keySet loop.
class Solution { private Map<Character, Set<Character>> dict; public String alienOrder(String[] words) { if (words.length == 0) { return ""; } dict = new HashMap<>(); for (String word : words) { for (char c : word.toCharArray()) { if (!dict.containsKey(c)) { dict.put(c, new HashSet<>()); } } } int total = dict.size(); for (int i = 0; i < words.length - 1; i++) { generateDependencies(words[i], words[i + 1]); } Queue<Character> queue = new LinkedList<>(); List<Character> toRemove = new ArrayList<>(); for (char c : dict.keySet()) { if (dict.get(c).size() == 0) { queue.offer(c); toRemove.add(c); } } dict.keySet().removeAll(toRemove); StringBuilder result = new StringBuilder(); while (!queue.isEmpty()) { int length = queue.size(); for (int i = 0; i < length; i++) { char current = queue.poll(); toRemove.clear(); for (char c : dict.keySet()) { if (dict.get(c).contains(current)) { dict.get(c).remove(new Character(current)); } if (dict.get(c).size() == 0) { queue.offer(c); toRemove.add(c); } } dict.keySet().removeAll(toRemove); result.append(current); } } return total == result.length() ? result.toString() : ""; } private void generateDependencies(String s1, String s2) { int index = 0; while (index < s1.length() && index < s2.length()) { if (s1.charAt(index) != s2.charAt(index)) { dict.get(s2.charAt(index)).add(s1.charAt(index)); break; } index++; } } }
以上是关于LeetCode 269: Alien Dictionary的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 269. Alien Dictionary 外文字典
leetcode269 - Alien Dictionary - hard