Advertisement
lifeiteng

269. Alien Dictionary

Sep 25th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. class Solution {
  2.     public String alienOrder(String[] words) {
  3.         int[] f = new int[26];
  4.         Arrays.fill(f, -1);
  5.         int distinct = 0;
  6.         Map<Integer, Set<Integer>> map = new HashMap<>();        
  7.         for(String w : words)
  8.         {
  9.             for(char ch : w.toCharArray())
  10.             {
  11.                 int idx = ch - 'a';
  12.                 if(f[idx] < 0)
  13.                 {
  14.                     f[idx] = 0;
  15.                     distinct++;
  16.                     map.put(idx, new HashSet<>());
  17.                 }
  18.             }
  19.         }
  20.         int n = words.length;
  21.         for(int i = 0; i < n - 1; i++)
  22.         {
  23.             String a = words[i], b = words[i + 1];
  24.             int l1 = a.length(), l2 = b.length(), len = Math.min(l1, l2);
  25.             if(a.equals(b)) continue;
  26.             int j = 0;
  27.             while(j < len && a.charAt(j) == b.charAt(j)) j++;
  28.             if(j == len) continue;   // case 'aa' and 'aaa' does not tell any information
  29.             // now i is the different character position
  30.             int idx0 = a.charAt(j) - 'a', idx1 = b.charAt(j) - 'a';
  31.             if(map.get(idx0).contains(idx1)) continue;
  32.             map.get(idx0).add(idx1);
  33.             f[idx1]++;
  34.         }
  35.         // System.out.println(map);
  36.         // System.out.println(Arrays.toString(f));
  37.         Queue<Integer> q = new LinkedList<>();
  38.         int[] re = new int[distinct];
  39.         int idx = 0;
  40.         for(int i = 0; i < 26; i++)
  41.         {
  42.             if(f[i] == 0) q.offer(i);
  43.         }
  44.         while(!q.isEmpty())
  45.         {
  46.             int from = q.poll();
  47.             re[idx++] = from;
  48.             for(int to : map.get(from))
  49.             {
  50.                 f[to]--;
  51.                 if(f[to] == 0) q.offer(to);
  52.             }
  53.         }
  54.         if(idx < distinct) return "";
  55.         StringBuilder sb = new StringBuilder();
  56.         for(int k : re) sb.append((char)('a' + k));
  57.         return sb.toString();
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement