• 剑指 Offer II 114. 外星文字典


    题面:

     题解:按照拓扑序即可。

    代码:

    class Solution {
    public:
        string alienOrder(vector<string>& words) {
              int n = words.size();
              string ans="";
              unordered_map<char, unordered_set<int> >g;
              unordered_map<char, int> d;
              string s1, s2;
              int n1, n2;
              for(int i = 0;i < n;i ++)
              {
                  for(auto t: words[i])
                   d[t]=0;
              }
              for(int i = 1;i < n;i ++)
              {
                  s1 = words[i - 1];
                  s2 = words[i];
                  n1 = s1.size();
                  n2 = s2.size();
                  int j;
                  for(j = 0;j < min(n1, n2); j++)
                  {
                      if(s1[j] != s2[j])
                      {
                          if(g[s1[j]].find(s2[j])==g[s1[j]].end())
                          {
                            d[s2[j]] ++;
                            g[s1[j]].insert(s2[j]);
                          }
                          break;
                      }
                  }
                  if(j == min(n1, n2)&&n1>n2)return "";
              }
              queue< char >q;
              for(auto t : d)
              {
                  auto c = t.first;
                  if(!d[c])
                  {
                      q.push(c);
                  }
              }
              while(q.size())
              {
                  auto u = q.front();
                  q.pop();
                  ans += u;
                  for(auto t: g[u])
                  {
                      d[t]--;
                      if(!d[t])
                      {
                          q.push(t);
                      }
                  }
              }
              //cout<<ans<<endl;
              if(ans.size() != d.size())return "";
              return ans;
        }
    };
  • 相关阅读:
    GDUFE ACM-1050
    hdu-2020
    hdu-2055
    hdu-2734
    GDUFE ACM-1145
    GDUFE ACM-1127
    GDUFE ACM-1126
    GDUFE ACM-1125
    GDUFE ACM-1124
    GDUFE ACM-1123
  • 原文地址:https://www.cnblogs.com/flyljz/p/15836585.html
Copyright © 2020-2023  润新知