[leetcode] 269. Alien Dictionary 解题报告

题目链接: https://leetcode.com/problems/alien-dictionary/

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:

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

思路: 真是麻烦的一笔的题, 让我想起当年写poj 1001的时候.

使用拓扑排序来解决这题吧. 用两个hash表, 一个来存每个出现过的字符的入度, 另一个来存一个字符指向的字符集合, 即一个字符应该在另外字符的前面. 然后就每次找出一个入度为0的字符, 并且更新这个字符指向的字符集入度减1. 如果还没有遍历完所有的字符, 但是找不到入度为0的字符了,那么说明无法排序, 返回"". 有一些情况就是可能一次会有几个入度为0的字符, 这样其实是没有严格的顺序的对这些字符, 这种情况就随便哪个都行.

代码如下:

class Solution {
public:
    string alienOrder(vector<string>& words) {
        if(words.size() ==0) return "";
        unordered_map<char, unordered_set<char>> table;
        unordered_map<char, int> indegree;
        string result;
        for(auto str: words)
            for(auto ch: str) indegree[ch] = 0;
        for(int i =0; i< words.size()-1; i++)
        {
            int x = 0;
            while(words[i+1][x] == words[i][x]) x++;
            if(x < words[i].size())
            {
                if(table[words[i][x]].count(words[i+1][x]) ==0)
                {
                    table[words[i][x]].insert(words[i+1][x]);
                    indegree[words[i+1][x]]++;
                }
            }   
        }
        for(int i = 0; i< indegree.size(); i++)
        {
            char ch = ' ';
            for(auto &val: indegree)
                if(val.second == 0)
                    ch = val.first;
            if(ch == ' ') return "";
            indegree[ch]--;
            for(auto &val: table[ch]) indegree[val]--;
            result += ch;
        }
        return result;
    }
};


你可能感兴趣的:(LeetCode,String,hash)