leetcode269 - Alien Dictionary - hard

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.

Example 1:

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

Output: "wertf"

Example 2:

Input:
[
  "z",
  "x"
]

Output: "zx"

Example 3:

Input:
[
  "z",
  "x",
  "z"
] 

Output: "" 

Explanation: The order is invalid, so return "".

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.
拓扑排序。每两个连续的单词进行比较,用他们第一个不一样的字符来判断顺序,比如wrt和wrf,t就应该在f之前。放到graph里也就是t->f。 细节: 1. indegree用一个26大小的vector就好 2. 比较两个单词的时候不要out of range,比到短的结尾就结束。 3. 一旦发现在同个pos上字母不一样了,更新图更新indegree完了就可以break出去了。因为比较之后的字母根本没有意义,ett在rftt前面只能说明e要在r前面。 4. graph用hashmap来表示out->[in’s],特别注意只有当in还没出现在out的mapping里的时候,indegree[in]才要更新,否则就count多次了。 5. corner case:abc,ab。解决办法:比较到短的word的结尾时,如果发现还没找到不一样的字母且first的长度大于second的长度,直接return""。   实现:
class Solution {
public:
    string alienOrder(vector<string>& words) {
        vector<int> indegree(26);
        unordered_map<char, unordered_set<char>> graph;
        for (string word: words){
            for (char c : word){
                if (graph.count(c)) continue;
                graph.insert({c, unordered_set<char>()});
            }
        }
        
        for (int i=1; i<words.size(); i++){
            string first = words[i-1];
            string second = words[i];
            int l = min(first.size(), second.size());
            for (int j=0; j<l; j++){
                if (first[j] != second[j]){
                    char out = first[j];
                    char in = second[j];
                    if (graph[out].count(in) == 0){
                        graph[out].insert(in);
                        indegree[in-'a']++;
                    }
                    break;
                }
                if (j == l-1 && first.size() > second.size())
                    return "";
            }
        }
        
        string res = "";
        queue<char> q;
        for (auto elem : graph){
            if (indegree[elem.first-'a'] == 0){
                q.push(elem.first);
            }
        }
        
        while (!q.empty()){
            char cur = q.front();
            q.pop();
            res += cur;
            for (char c : graph[cur]){
                indegree[c-'a']--;
                if (indegree[c-'a'] == 0){
                    q.push(c);
                }
            }
        }

        return res.size() == graph.size()? res : "";
      
    }
};

 

上一篇:Alien Skin Exposure for Win/Mac中文激活破解版-(PS插件)专业的胶片调色软件


下一篇:Python实现飞机大战(搞怪)游戏!这是你没见过的全新版本!