|
| 1 | +/** |
| 2 | + * [Problem]: [892] Alien Dictionary |
| 3 | + * (https://www.lintcode.com/problem/892/) |
| 4 | + */ |
| 5 | + |
| 6 | +//시간복잡도 O(n+e) |
| 7 | +//공간복잡도 O(n+e) |
| 8 | +export class Solution { |
| 9 | + /** |
| 10 | + * @param words: a list of words |
| 11 | + * @return: a string which is correct order |
| 12 | + */ |
| 13 | + alienOrder(words: string[]): string { |
| 14 | + // Write your code here |
| 15 | + const graph: Map<string, Set<string>> = new Map(); |
| 16 | + |
| 17 | + // 모든 문자를 그래프 노드로 초기화 |
| 18 | + for (const word of words) { |
| 19 | + for (const char of word) { |
| 20 | + if (!graph.has(char)) { |
| 21 | + graph.set(char, new Set()); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + // 문자 간 선후관계(edge) 설정 |
| 27 | + for (let i = 1; i < words.length; i++) { |
| 28 | + const prev = words[i - 1]; |
| 29 | + const curr = words[i]; |
| 30 | + let isDiff = false; |
| 31 | + |
| 32 | + for (let j = 0; j < Math.min(prev.length, curr.length); j++) { |
| 33 | + const p = prev[j]; |
| 34 | + const c = curr[j]; |
| 35 | + |
| 36 | + if (p !== c) { |
| 37 | + graph.get(p)!.add(c); |
| 38 | + isDiff = true; |
| 39 | + break; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if (!isDiff && prev.length > curr.length) { |
| 44 | + return ""; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + const visited: Set<string> = new Set(); |
| 49 | + const visiting: Set<string> = new Set(); |
| 50 | + const output: string[] = []; |
| 51 | + |
| 52 | + function dfs(node: string): boolean { |
| 53 | + if (visited.has(node)) return true; |
| 54 | + if (visiting.has(node)) return false; |
| 55 | + |
| 56 | + visiting.add(node); |
| 57 | + |
| 58 | + for (const neighbor of graph.get(node)!) { |
| 59 | + if (!dfs(neighbor)) return false; |
| 60 | + } |
| 61 | + |
| 62 | + visiting.delete(node); |
| 63 | + visited.add(node); |
| 64 | + output.push(node); |
| 65 | + |
| 66 | + return true; |
| 67 | + } |
| 68 | + |
| 69 | + for (const node of graph.keys()) { |
| 70 | + if (!dfs(node)) return ""; |
| 71 | + } |
| 72 | + |
| 73 | + return output.reverse().join(""); |
| 74 | + } |
| 75 | +} |
0 commit comments