1. 程式人生 > >LeetCode(269) Alien Dictionary (Java)

LeetCode(269) Alien Dictionary (Java)

題目如下:

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.

分析:

先看上面的例子。

先看所有單詞的第0個字元,可以知道先後順序是w->e-r。

再看第1個字元,先後順序是r->t,

再看第3個字元,先後順序是t->f

當有有了若干部分的依賴關係之後,想得到完成的排序,那麼可以考慮拓撲排序。雖然聽上去很基本,但是程式碼處理起來有很多細節需要注意。

從這位大神的討論帖裡學到很簡潔的C++程式碼: 先構造合適的依賴關係,然後進行拓撲排序。

我搬運之並修改為Java

public class Solution {
    public String alienOrder(String[] words) {
        if (words == null || words.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        HashMap<Character, Set<Character>> suc = new HashMap<Character, Set<Character>>();
        HashMap<Character, Integer> pre = new HashMap<Character, Integer> ();
        HashSet<Character> charSet = new HashSet<Character>();
        String previousWord = new String("");
        for (String currentWord : words) {
            for (Character c : currentWord.toCharArray()) {
                charSet.add(c);
            }
            for (int i = 0; i < Math.min(previousWord.length(), currentWord.length()); ++i) {
                if (previousWord.charAt(i) != currentWord.charAt(i)) {
                    if (!pre.containsKey(currentWord.charAt(i))) { //----section_pre----
                        pre.put(currentWord.charAt(i), 1);
                    } else {
                        //ERROR1: 過濾掉重複的關係 ["za","zb","ca","cb"], 從輸入得出的中間結論,"a->b"會重複出現兩次,需要濾重。為了實現濾重,重新調整了section_pre和section_suc部分的順序。
                        if (suc.containsKey(previousWord.charAt(i)) && 
                        suc.get(previousWord.charAt(i)).contains(currentWord.charAt(i))) {
                            continue;
                        }
                        pre.put(currentWord.charAt(i), pre.get(currentWord.charAt(i)) + 1);
                    }
                    if (!suc.containsKey(previousWord.charAt(i))) { //----section_suc----
                        suc.put(previousWord.charAt(i), new HashSet<Character> ());
                    }
                    suc.get(previousWord.charAt(i)).add(currentWord.charAt(i));                    
                    break; //the BEST part of this question
                }
            }
            previousWord = currentWord;
        }
        Queue<Character> queue = new LinkedList<Character>();
        for (Character each : charSet) {
            if (!pre.containsKey(each)) {
                queue.add(each);
            }
        }


        while (!queue.isEmpty()) {
            Character currentChar = queue.poll();
            sb.append(currentChar);
            //ERROR2 should check containsKey
            if (!suc.containsKey(currentChar)) {
                continue;
            }
            for (Character each : suc.get(currentChar)) {
                pre.put(each, pre.get(each) - 1);
                if (pre.get(each) == 0) {
                    queue.offer(each);
                }
            }
        }
        return sb.length() == charSet.size() ? sb.toString() : "";
    }
}