269. Alien Dictionary

set中没有c2的时候再去增加c2的degree 不然会出错

 

 1 class Solution {
 2     public String alienOrder(String[] words) {
 3         if(words.length == 0) return "";
 4         HashMap<Character, HashSet<Character>> map = new HashMap<>();
 5         HashMap<Character, Integer> degree = new HashMap<>();
 6         for(String word : words){
 7             for(char c : word.toCharArray()){
 8                 degree.put(c, 0);
 9             }
10         }
11         for(int i = 0; i < words.length - 1; i++){
12             String word1 = words[i];
13             String word2 = words[i+1];
14             int length = Math.min(word1.length(), word2.length());
15             for(int j = 0; j < length; j++){
16                 char c1 = word1.charAt(j);
17                 char c2 = word2.charAt(j);
18                 if(c1 != c2){
19                     if(!map.containsKey(c1)){
20                         map.put(c1, new HashSet<>());
21                     }
22                     if(!map.get(c1).contains(c2)){
23                        map.get(c1).add(c2);
24                         degree.put(c2, degree.get(c2)+1);
25                         
26                     }
27                     break; //在外面   
28                 }
29                 
30             }
31         }
32         Queue<Character> queue = new LinkedList<>();
33         for(char c : degree.keySet()){
34             if(degree.get(c) == 0){
35                 queue.offer(c);
36                 
37             }
38         }
39         String res = "";
40         while(!queue.isEmpty()){
41             char c = queue.poll();
42             res += c;
43             if(map.containsKey(c)){
44                 for(char c1 : map.get(c)){
45                     degree.put(c1, degree.get(c1)-1);
46                     if(degree.get(c1) == 0){
47                         queue.offer(c1);
48                     }
49                 }
50             }
51             
52             
53         }
54         // System.out.println(degree.get('b'));
55         if(res.length() != degree.size()) return "";
56         return res;
57         
58     }
59 }

 

posted @ 2018-11-27 01:25  jasoncool1  阅读(164)  评论(0编辑  收藏  举报