zoukankan      html  css  js  c++  java
  • 269. 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 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.
    #include<iostream>
    #include<string>
    #include<vector>
    #include<set>
    #include<map>
    using namespace std;
    
    string getOrder(vector<string>& v)
    {
        int n = v.size(), i, j;
        if (n < 1)
            return "";
        set<char> st;
        for (i = 0; i < n; i++)
        {
            for (j = 0; j < v[i].size(); j++)
                st.insert(v[i][j]);
        }
        map<char, set<char>> mp;
        for (set<char>::iterator it = st.begin(); it != st.end(); it++)
            mp[*it] = set<char>();
        string ans = "";
        for (i = 1; i < n; i++)
        {
            for (j = 0; j < v[i].size() && j < v[i - 1].size(); j++)
            {
                if (v[i][j] != v[i - 1][j])
                {
                    mp[v[i][j]].insert(v[i - 1][j]);
                    break;
                }
            }
        }
        while (!mp.empty())
        {
            int num = 0;
            for (map<char, set<char>>::iterator it = mp.begin(); it != mp.end(); )
            {
                if ((it->second).empty())
                {
                    char c = it->first;
                    ans += c;
                    mp.erase(it++);
                    num++;
                    for (map<char, set<char>>::iterator iter = mp.begin(); iter != mp.end(); iter++)
                        iter->second.erase(c);
                }
                else
                    it++;
            }
            if (0 == num)
                return "";
        }
        return ans;
    }
    
    int main()
    {
        vector<string> v;
        v.push_back("w");
        v.push_back("t");
        v.push_back("e");
        v.push_back("r");
        v.push_back("rf");
        cout << getOrder(v) << endl;
        return 0;
    }

    st:所有出现的字母的集合。

    mp:每个字母有一个set,为在这个字母之前的字母的集合。

    拓扑排序。

  • 相关阅读:
    SQL INNER JOIN
    SQL JOIN
    SQL OUTER JOIN
    SQL CROSS JOIN
    SQL 基础:Select语句,各种join,union用法
    Morton Code
    vs 字体
    sql 语言
    sqllite3
    linux怎么区别文本文件和二进制文件
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5976240.html
Copyright © 2011-2022 走看看