|
| 1 | +class Solution { |
| 2 | + /** |
| 3 | + * @param words: a list of words |
| 4 | + * @return: a string which is correct order |
| 5 | + */ |
| 6 | + fun alienOrder(words: Array<String>): String { |
| 7 | + // Write your code here |
| 8 | + val adj = List<MutableList<Int>>('z'.code - 'a'.code + 1) {mutableListOf()} |
| 9 | + for (i in 1 until words.size) { |
| 10 | + var j = 0 |
| 11 | + while (j != words[i - 1].length && j != words[i].length && words[i - 1][j] == words[i][j]) { |
| 12 | + j++ |
| 13 | + } |
| 14 | + if (j == words[i - 1].length) { |
| 15 | + continue |
| 16 | + } |
| 17 | + if (j == words[i].length) { |
| 18 | + return "" |
| 19 | + } |
| 20 | + adj[words[i - 1][j].code - 'a'.code].add(words[i][j].code - 'a'.code) |
| 21 | + } |
| 22 | + val visited = MutableList(adj.size) {false} |
| 23 | + words.forEach { |
| 24 | + it.map { it.code - 'a'.code } |
| 25 | + .forEach { visited[it] = true } |
| 26 | + } |
| 27 | + val inDegrees = MutableList(adj.size) {0} // Kahn T(V, E) = S(V, E) = O(V + E) |
| 28 | + adj.forEach { |
| 29 | + it.forEach { inDegrees[it]++ } |
| 30 | + } |
| 31 | + val ans = mutableListOf<Int>() |
| 32 | + val stack = mutableListOf<Int>() |
| 33 | + (0 until adj.size).filter { visited[it] && inDegrees[it] == 0 } |
| 34 | + .forEach { |
| 35 | + stack.add(it) |
| 36 | + ans.add(it) |
| 37 | + } |
| 38 | + while (! stack.isEmpty()) { |
| 39 | + val u = stack.removeLast() |
| 40 | + adj[u].forEach { |
| 41 | + if (--inDegrees[it] == 0) { |
| 42 | + stack.add(it) |
| 43 | + ans.add(it) |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + if ((0 until adj.size).any { visited[it] && inDegrees[it] != 0 }) { |
| 48 | + return "" |
| 49 | + } |
| 50 | + return ans.map { (it + 'a'.code).toChar() } |
| 51 | + .joinToString("") |
| 52 | + /*val decoder = MutableList(adj.size) {0} |
| 53 | + (0 until ans.size).forEach { decoder[ans[it]] = it } |
| 54 | + val decoded = words.map { |
| 55 | + it.map { (decoder[it.code - 'a'.code] + 'a'.code).toChar() } |
| 56 | + .joinToString("") |
| 57 | + } |
| 58 | + val sortedWords = decoded.sorted() |
| 59 | + return if (decoded == sortedWords) ans.map { (it + 'a'.code).toChar() } |
| 60 | + .joinToString("") |
| 61 | + else ""*/ |
| 62 | + } |
| 63 | +} |
0 commit comments