Skip to content

Instantly share code, notes, and snippets.

@kiro
Created June 5, 2019 04:10
Show Gist options
  • Save kiro/b5d170f368893824c5c5e0234002d89e to your computer and use it in GitHub Desktop.
Save kiro/b5d170f368893824c5c5e0234002d89e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
var before [26][26]bool
var used[26]bool
func filter(arr []string, j int) []string {
result := []string{}
for _, s := range arr {
if len(s) > j {
result = append(result, s)
}
}
return result
}
func order(arr []string, j int) {
arr = filter(arr, j)
if len(arr) == 0 {
return
}
p := 0
for i := 1; i < len(arr); i++ {
used[arr[i][j] - 'a'] = true
if arr[i][j] != arr[i-1][j] {
before[arr[i-1][j]-'a'][arr[i][j] - 'a'] = true
order(arr[p:i], j+1)
p = i
}
}
order(arr[p:], j+1)
}
func topsort(u int, seen map[int]bool, result *[]string) {
if seen[u] {
return
}
for v := 0; v < 26; v++ {
if before[v][u] {
topsort(v, seen, result)
}
}
seen[u] = true
*result = append(*result, string('a' + u))
}
func main() {
arr := []string{"xww", "wxyz", "wxyw", "ywx", "ywz"}
order(arr, 0)
seen := make(map[int]bool)
result := make([]string, 0)
for i := 25; i >= 0; i-- {
if used[i] {
topsort(i, seen, &result)
}
}
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment