269. Alien Dictionary解題報告

Description:

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 non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Note:
You may assume all letters are in lowercase.
You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.

Example:

Example 1:

Given the following words in dictionary,

[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]
The correct order is: "wertf".

Example 2:

Given the following words in dictionary,

[
  "z",
  "x"
]
The correct order is: "zx".

Example 3:

Given the following words in dictionary,

[
  "z",
  "x",
  "z"
]
The order is invalid, so return "".

Link:

https://leetcode.com/problems/alien-dictionary/description/

解題方法:

這是一道圖求環的題。
第一步:
直接遍歷輸入數組,從每兩個相連的單詞查找已有的先后順序信息。
例如:abc, abd
可以得出:c > d
因為輸入的單詞是由詞典順序排序的,所以不會存在不相鄰的兩個單詞也有必要的順序信息。
將得到的信息存在哈希表里。
第二步:
對圖進行求環,這里我用的是DFS的方法,雖然BFS更快,但是這道題決定時間復雜度的在于遍歷單詞的每個字母。
在DFS的同時計算每個單詞依照語言順序后面有多少個字母。(用hash_set來統計)
如果圖中有環,說明有沖突,沒有一個有效的字母順序。
如果有字母存在相同的統計結果,我們只要輸出其中的一種。
第三步:
對以上統計結果(字母-->該字母依照語言順序后面有多少個字母)排序(降序),求出結果即為我們需要的結果。

Tips:

Time Complexity:

O(N) N為所有單詞所有字母的總和

完整代碼:

string alienOrder(vector<string>& words) {
    int len = words.size();
    if(!len)
        return "";
    if(len == 1)
        return words[0];
    //get rules between two characters (build Graph)
    unordered_map<char, unordered_set<char>> characters;
    for(int i = len - 1; i > 0; i--) {
        string str2 = words[i];
        string str1 = words[i - 1];
        for(char cha: str1)
            if(characters.find(cha) == characters.end())
                characters[cha] = unordered_set<char>();
        for(char cha: str2)
            if(characters.find(cha) == characters.end())
                characters[cha] = unordered_set<char>();
        for(int i = 0; i < str1.size() && i < str2.size(); i++) {
            if(str1[i] != str2[i]) {
                characters[str1[i]].insert(str2[i]);
                break;
            }
        }
    }
    //DFS
    vector<pair<char, int>> order;
    for(auto a: characters) {
        bool valid = true;
        unordered_set<char> visited;
        unordered_set<char> count;
        visited.insert(a.first);
        dfs(a.first, characters, valid, visited, count);
        order.push_back(pair<char, int>(a.first, count.size()));
        if(!valid)
            return "";
    }        
    //sort
    sort(order.begin(), order.end(), [](pair<char, int> a, pair<char, int> b){
        return a.second > b.second;
    });

    //build result
    string result = "";
    for(auto a: order) {
        result += a.first;
    }
    return result;
}
void dfs(char curr, unordered_map<char, unordered_set<char>>& characters, bool& valid, unordered_set<char>& visited, unordered_set<char>& count) {
    count.insert(curr);
    if(!valid || characters[curr].empty())
        return;
    for(auto a: characters[curr]) {
        if(visited.find(a) != visited.end()) {
            valid = false;
            return;
        }
        visited.insert(a);
        dfs(a, characters, valid, visited, count);
        visited.erase(a);
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,939評論 0 23
  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,776評論 0 33
  • 說話太直,做事考慮不全面,我在這漫漫的成長路上惹怒了不少人,結怨了不少人。 三歲學說話,一生學閉嘴,學會閉嘴真是我...
    小呀小阿瑤閱讀 195評論 0 0
  • 前一段時間看到一篇名為《面試公司說培訓我,結果我背了幾萬元的債》的文章,說是現代金融產品的變現能力形式多樣,一不小...
    子墨素鳶閱讀 1,080評論 0 7
  • 最近我的侄兒大鵬吵著要改名字。90后的侄兒覺得“大鵬”二字,特俗,想改個時尚好聽的名字,家人一致反對?!按?..
    毛小驢613閱讀 207評論 0 0