首页 > 其他 > 详细

LeetCode 269: Alien Dictionary

时间:2017-09-05 17:23:53      阅读:283      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/shuashuashua/p/7479631.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!