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++;
        }
    }
}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7479631.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值