There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

For example, Given the following words in dictionary,

[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]

The correct order is: "wertf".

Note: You may assume all letters are in lowercase. If the order is invalid, return an empty string. There may be multiple valid order of letters, return any one of them is fine.

Solution

public class Solution {
    public String alienOrder(String[] words) {
        Map<Character, Set<Character>> map = new HashMap<Character, Set<Character>>();
        int[] indegree = new int[128];

        for(int i = 0; i < words.length; i++) {
            for(char c: words[i].toCharArray()) {
                if(!map.containsKey(c)) map.put(c, new HashSet<Character>());
            }

            if(i != words.length - 1) {
                // find the first different, and add the edge
                for(int j = 0; j < Integer.min(words[i].length(), words[i+1].length()); j++) {
                    char s = words[i].charAt(j);
                    char e = words[i+1].charAt(j);
                    if(s != e) {
                        // need to make sure there is no circle
                        // make sure words[i] <= words[i+1]
                        if(map.get(s).add(e)) indegree[e]++;
                        break;
                    }

                }


            }
        }

        Queue<Character> queue = new LinkedList<Character>();
        for(Character c: map.keySet()) {
            if(indegree[c] == 0) {
                queue.offer(c);
            }
        }

        int order[] = new int[128];
        int cnt = 0;
        StringBuilder sb = new StringBuilder();
        while(!queue.isEmpty()) {
            Character c = queue.poll();
            sb.append(c);
            for(Character dst: map.get(c)) {
                if(--indegree[dst] == 0) {
                    queue.offer(dst);
                }
            }
            order[c] = cnt++;
        }


        if(sb.length() != map.keySet().size()) return ""; // topological sort is invalid

        for(int i = 1; i < words.length; i++) {
            boolean same = true;
            for(int j = 0; j < Integer.min(words[i-1].length(), words[i].length()); j++) {
                if(words[i-1].charAt(j) != words[i].charAt(j)) {
                    if( order[words[i-1].charAt(j)] > order[words[i].charAt(j)]) return "";
                    same = false;
                    break;
                }
            }
            if(same && words[i-1].length() > words[i].length()) return "";
        }

        return sb.toString();
    }
}

results matching ""

    No results matching ""