|
| 1 | +/** |
| 2 | + * TC: O(W * S) |
| 3 | + * 4번에서 W만큼 순회 * 메모이제이션 S |
| 4 | + * |
| 5 | + * SC: O(S) |
| 6 | + * queue 최대 S + visited 최대 S |
| 7 | + * |
| 8 | + * S: s.length, W: wordDict.length |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * @param {string} s |
| 13 | + * @param {string[]} wordDict |
| 14 | + * @return {boolean} |
| 15 | + */ |
| 16 | +var wordBreak = function (s, wordDict) { |
| 17 | + const queue = [0]; |
| 18 | + const visited = new Set(); |
| 19 | + |
| 20 | + while (queue.length) { |
| 21 | + const start = queue.shift(); |
| 22 | + // 1. 도착했다면 정답 반환 |
| 23 | + if (start === s.length) { |
| 24 | + return true; |
| 25 | + } |
| 26 | + // 2. 이미 방문한 경우 순회 방지 |
| 27 | + if (visited.has(start)) { |
| 28 | + continue; |
| 29 | + } |
| 30 | + |
| 31 | + // 3. 방문 표시 남기고 |
| 32 | + visited.add(start); |
| 33 | + // 4. wordDict의 word를 이용할 있는 경우 |
| 34 | + for (const word of wordDict) { |
| 35 | + if (s.slice(start, start + word.length) === word) { |
| 36 | + queue.push(start + word.length); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return false; |
| 42 | +}; |
| 43 | + |
| 44 | +/** |
| 45 | + * TC: O(W * S) |
| 46 | + * 2번에서 W만큼 순회 * 메모이제이션 S |
| 47 | + * |
| 48 | + * SC: O(S) |
| 49 | + * possibleS의 길이 S + dfs의 깊이는 최대 S |
| 50 | + * |
| 51 | + * S: s.length, W: wordDict.length |
| 52 | + */ |
| 53 | + |
| 54 | +/** |
| 55 | + * @param {string} s |
| 56 | + * @param {string[]} wordDict |
| 57 | + * @return {boolean} |
| 58 | + */ |
| 59 | +var wordBreak = function (s, wordDict) { |
| 60 | + // 1. S의 index번째 글자까지 wordDict 조합이 가능한지 표시하는 배열 |
| 61 | + const possibleS = new Array(s.length + 1).fill(false); |
| 62 | + |
| 63 | + dfs(0); |
| 64 | + |
| 65 | + return possibleS[s.length]; |
| 66 | + |
| 67 | + function dfs(start) { |
| 68 | + // 2. wordDict의 word를 이용할 있는 경우 |
| 69 | + for (const word of wordDict) { |
| 70 | + if (s.slice(start, start + word.length) === word) { |
| 71 | + // 3. 이미 조합 가능 표시가 있는 index의 경우 백트래킹 |
| 72 | + if (possibleS[start + word.length]) { |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + // 4. 조합 가능하다는 표시를 하고 다음 index로 재귀 |
| 77 | + possibleS[start + word.length] = true; |
| 78 | + dfs(start + word.length); |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | +}; |
0 commit comments