Created
June 16, 2016 01:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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