|
| 1 | +''' |
| 2 | +ํ์ด |
| 3 | +- BFS์ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ๊ธฐ๋กํ๋ ๋ฐฉ์์ ์ด์ฉํ์ฌ ํ์ดํ ์ ์์ต๋๋ค |
| 4 | +- ์ฃผ์ด์ง ๋ฌธ์์ด s์ ๊ธธ์ด n๋ณด๋ค 1 ๋ ํฐ ํฌ๊ธฐ์ ๋ฐฐ์ด visit์ False๋ก ์ด๊ธฐํํด์ค๋๋ค |
| 5 | + n + 1๋ก ์ค์ ํ๋ ์ด์ ๋ BFS ์ค๊ณ๋ฅผ ์ฝ๊ฒ ํ๊ธฐ ์ํจ์
๋๋ค |
| 6 | +- queue ๊ธฐ๋ฅ์ ํด์ค deque์ธ dq๋ฅผ ์์ฑํด์ฃผ๊ณ ์ด๊ธฐ๊ฐ์ผ๋ก 0์ ์ฝ์
ํฉ๋๋ค |
| 7 | + dq์ ์์ curr๊ฐ ๊ฐ๋ ์๋ฏธ๋ `ํ์ฌ ํ์ ์ค์ธ substring์ ์์ index, ์ฆ s[curr:]์
๋๋ค` |
| 8 | +- while๋ฌธ์ ์งํํ๋ฉฐ dq์์ curr๋ฅผ popํด์ค๋๋ค |
| 9 | + ๋ง์ฝ curr๋ฅผ ํ์ํ ์ ์ด ์๋ค๋ฉด ์ง๋์น๊ณ , ํ์ํ ์ ์ด ์๋ค๋ฉด starts_with ํจ์๋ฅผ ์คํํ๊ณ |
| 10 | + ๊ทธ ์ฌ๋ถ์ ๋ฐ๋ผ dq์ curr๋ฅผ ์ถ๊ฐ ๋ฐ visit์ ๊ฐฑ์ ํฉ๋๋ค |
| 11 | +
|
| 12 | +Big O |
| 13 | +- N: ์ฃผ์ด์ง ๋ฌธ์์ด s์ ๊ธธ์ด |
| 14 | +- M: ์ฃผ์ด์ง ๋ฌธ์์ด ๋ฐฐ์ด wordDict์ ๋ชจ๋ ๋ฌธ์์ด์ ๊ธธ์ด์ ํฉ |
| 15 | +
|
| 16 | +- Time complexity: O(N * M) |
| 17 | + - visit ๋ฐฐ์ด๋ก ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ๊ด๋ฆฌํ๊ธฐ ๋๋ฌธ์ ํ์์ ์ต๋ N๋ฒ ์ด๋ค์ง๋๋ค |
| 18 | + - ๊ฐ ํ์๋ง๋ค wordDict๋ฅผ ์ํํ๋ฉฐ starts_with๋ฅผ ์คํํ๋๋ฐ ์ด ์คํ ์๊ฐ์ M์ด ์ฆ๊ฐํจ์ ๋ฐ๋ผ ์ ํ์ ์ผ๋ก ์ฆ๊ฐํฉ๋๋ค |
| 19 | +
|
| 20 | +- Space complexity: O(N) |
| 21 | + - visit ๋ฐฐ์ด์ ํฌ๊ธฐ๋ N์ด ์ฆ๊ฐํจ์ ๋ฐ๋ผ ์ ํ์ ์ผ๋ก ์ฆ๊ฐํฉ๋๋ค |
| 22 | + - deque์ ๋ด๊ธด ์์์ ์๋ ์ต๋ N๊น์ง ์ฆ๊ฐํ ์ ์์ต๋๋ค |
| 23 | +''' |
| 24 | + |
| 25 | +class Solution: |
| 26 | + def wordBreak(self, s: str, wordDict: List[str]) -> bool: |
| 27 | + n = len(s) |
| 28 | + visit = [False] * (n + 1) |
| 29 | + |
| 30 | + def starts_with(idx: int, word: str) -> bool: |
| 31 | + m = len(word) |
| 32 | + for i in range(m): |
| 33 | + if s[idx + i] != word[i]: |
| 34 | + return False |
| 35 | + return True |
| 36 | + |
| 37 | + dq = deque([0]) |
| 38 | + |
| 39 | + while dq: |
| 40 | + curr = dq.popleft() |
| 41 | + |
| 42 | + if curr == len(s): |
| 43 | + return True |
| 44 | + |
| 45 | + for word in wordDict: |
| 46 | + m = len(word) |
| 47 | + if curr + m <= n and not visit[curr + m] and starts_with(curr, word): |
| 48 | + dq.append(curr + m) |
| 49 | + visit[curr + m] = True |
| 50 | + |
| 51 | + return False |
0 commit comments