LeetCode 269. Alien Dictionary

本文介绍了一种基于拓扑排序的算法,该算法能够从一组按未知外星语言字典序排列的单词中推断出该语言字母的正确顺序。通过构建有向无环图并使用深度优先搜索进行遍历,最终得出字母间的相对顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This solution is not done yet. I didn't check the validation of DAG.

#include <vector>
#include <string>
#include <iostream>
#include <stack>
#include <unordered_map>
#include <unordered_set>
using namespace std;

/*
  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 the dictionary.
  ["wrt", "wrf", "er", "ett", "rftt"] the correct order is "wertf"
  Note:
    You may assume all letters are in lowercase
    If the order is invalid, return an emtpy string
    There may be multiple valid order of letters, return any one of them is fine.
*/
// this is to apply topological sort, But, we need to build graph first.
void dfs(unordered_map<char, bool>& visited, unordered_map<char, unordered_set<char> >& charSequence, stack<char>& res, char tmp) {
  visited[tmp] = true;
  unordered_set<char> edges = charSequence[tmp];
  auto iter = edges.begin();
  while(iter != edges.end()) {
    if(!visited[*iter]) {
      dfs(visited, charSequence, res, *iter);
    }
    iter++;
  }
  res.push(tmp);
}
string alienOrder(vector<string> words) {
  if(words.size() == 0) return "";
  unordered_map<char, unordered_set<char> > charSequence;
  unordered_set<char> chars;
  for(int i = 0; i < words.size(); ++i) {
    for(int j = 0; j < words[i].size(); ++j) {
      chars.insert(words[i][j]);
    }

    for(int j = 0; j < words[i].size() - 1; ++j) {
      for(int k = j + 1; k < words[i].size(); ++k) {
        if(words[i][j] == words[i][k]) continue;      // if the prev and next char is repeat, skip it.
        charSequence[words[i][j]].insert(words[i][k]);  // it is important here to use unordered_set to kick out repeats. 
      }
    }
  }

  // building of DAG is done now.
  int n = chars.size();
  unordered_map<char, bool> visited;
  auto iter = chars.begin();
  while(iter != chars.end()) {
    visited[*iter] = false;
    iter++;
  }
  stack<char> res;
  iter = chars.begin();
  while(iter != chars.end()) {
    if(!visited[*iter]) {
      dfs(visited, charSequence, res, *iter);
    }
    iter++;
  }
  string result = "";
  while(!res.empty()) {
    char tmp = res.top();
    result += tmp;
    res.pop();
  }
  return result;
}

int main(void) {
  vector<string> words{"wrt", "wrf", "er", "ett", "rftt"};
  string res = alienOrder(words);
  cout << res << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值