Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created June 16, 2016 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/07546625d828f63e762ba03b463fe8aa to your computer and use it in GitHub Desktop.
Save jianminchen/07546625d828f63e762ba03b463fe8aa to your computer and use it in GitHub Desktop.
Leetcode 269 - Alien Dictionary - source code from blog: http://www.cnblogs.com/yrbbest/p/5023584.html -> C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _269AlienDictionary
{
class Program
{
static void Main(string[] args)
{
}
/*
* source code from blog:
* http://www.cnblogs.com/yrbbest/p/5023584.html
*
* Topological sorting - Kahn's Algorithm
*/
public String alienOrder(String[] words) {
if(words == null || words.Length == 0) {
return "";
}
Dictionary<char, HashSet<char>> graph = new Dictionary<char, HashSet<char>>();
HashSet<char> set = new HashSet<char>();
foreach (string word in words) {
for (int i = 0; i < word.Length; i++) {
set.Add(word[i]);
}
}
int[] inDegree = new int[26];
for (int k = 1; k < words.Length; k++) {
String preStr = words[k - 1];
String curStr = words[k];
for (int i = 0; i < Math.Min(preStr.Length, curStr.Length); i++) {
char preChar = preStr[i];
char curChar = curStr[i];
if (preChar != curChar) {
if (!graph.ContainsKey(preChar)) {
graph.Add(preChar, new HashSet<char>());
}
if (!graph[preChar].Contains(curChar)) {
inDegree[curChar - 'a']++;
}
graph[preChar].Add(curChar);
break;
}
}
}
Queue<char> queue = new Queue<char>();
for (int i = 0; i < inDegree.Length; i++) {
if (inDegree[i] == 0) {
char c = (char)('a' + i);
if (set.Contains(c)) {
queue.Enqueue(c);
}
}
}
StringBuilder sb = new StringBuilder();
while (queue.Count > 0) {
char c = queue.Peek();
sb.Append(c);
if (graph.ContainsKey(c)) {
foreach (char l in graph[c]) {
inDegree[l - 'a']--;
if (inDegree[l - 'a'] == 0) {
queue.Enqueue(l);
}
}
}
}
return sb.Length != set.Count ? "" : sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment