码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 269: Alien Dictionary

时间:2017-09-05 17:47:14      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:sid   UI   bsp   case   tor   linked   nts   alien   void   

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

标签:sid   UI   bsp   case   tor   linked   nts   alien   void   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!