Alien Dictionary

题目链接:https://leetcode.com/problems...

图用topological sort,和course schedule题类似。
要找到所有字母的indegree,之后用q存下入度为0的字母,然后输出。要记录下每个字母对应的所有parent字母,防止重复。求indegree的过程可以用dfs,从所有单词的index = 0开始,对不同的字母存入度,相同的去下一层。

注意invalid的情况:有环,如果出现两个单词start相同,那么长度短的在前:["ab", "abc"]

public class Solution {
    public String alienOrder(String[] words) {
        init(words);
        getGraph(list, 0);
        if(!valid) return "";
        
        // find the character with indegree = 0
        Queue<Character> q = new LinkedList();
        for(int i = 0; i < indegree.length; i++) {
            if(indegree[i] == 0 && set.contains(i)) {
                q.offer((char) (i + 'a'));
            }
        }
        
        String result = "";
        while(!q.isEmpty()) {
            char c = q.poll();
            result += c;
            // if indegree -> 0, add to the q
            for(Character child : parents.get(c - 'a')) {
                if(--indegree[child - 'a'] == 0) {
                    q.offer(child);
                }
            }
        }
        
        return result;
    }
    
    int[] indegree;
    List<Set<Character>> parents;
    // record the appearred characters
    Set<Integer> set = new HashSet();
    List<String> list;
    boolean valid = true;
    
    private void init(String[] words) {
        indegree = new int[26];
        parents = new ArrayList();
        for(int i = 0; i < 26; i++) parents.add(new HashSet());
        
        list = new ArrayList();
        for(String word : words) {
            list.add(word);
            for(int i = 0; i < word.length(); i++) set.add(word.charAt(i) - 'a');
        }
    }
    
    private void getGraph(List<String> list, int level) {
        // base case
        if(list.size() == 0) return;
        
        for(int i = 0; i < list.size(); i++) {
            if(level >= list.get(i).length()) {
                continue;
            }
            char c = list.get(i).charAt(level);
            // record the string with the same character at current level
            List<String> same = new ArrayList();
            same.add(list.get(i));
            for(int j = i+1; j < list.size(); j++) {
                String cur = list.get(j);
                if(cur.length() <= level) {
                    // same start, different len, [abc, ab] is invalid
                    valid = false;
                    continue;
                }
                // character in the same level has order
                else if(cur.charAt(level) != c) {
                    if(parents.get(c-'a').add(cur.charAt(level))) {
                        indegree[cur.charAt(level) - 'a']++;
                        if(parents.get(cur.charAt(level)-'a').contains(c)) valid = false;
                    }
                }
                else same.add(cur);
            }
            if(same.size() > 1) getGraph(same, level + 1);
        }
    }
}

indegree用hashmap更好,这样就不用单独的再用个set保存出现过的字母了。
bfs的方法:待做。。


lulouch13
13 声望6 粉丝