Skip to content

Commit 7ce4ff6

Browse files
committed
word break solution
1 parent 21e3894 commit 7ce4ff6

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

โ€Žword-break/radiantchoi.pyโ€Ž

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def traverse(self, s: str, wordDict: List[str], checked: int, memo: Dict[int,bool]) -> bool:
3+
# checked์˜ ์˜๋ฏธ: ํ˜„์žฌ๊นŒ์ง€ ์ฒดํฌํ•œ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด - ์•„์ง ์—ฌ๊ธฐ์„œ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ๋๊นŒ์ง€ ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์žฅ๋‹ดํ•  ์ˆ˜ ์—†์Œ
4+
# ์‹œ์ž‘ ์ธ๋ฑ์Šค๊ฐ€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด์™€ ๊ฐ™์€ ๊ฒฝ์šฐ, ์ด ๋ฌธ์ž์—ด์— ๋Œ€ํ•ด ๊ฒ€์‚ฌ๋ฅผ ๋งˆ์ณค๋‹ค๋Š” ๋œป (๋‚จ์€ ๊ธธ์ด๊ฐ€ 0)
5+
if checked == len(s):
6+
return True
7+
8+
# ์ง€๊ธˆ ๋‹ค๋ฃจ๋ ค๋Š” ์ธ๋ฑ์Šค๋ฅผ ์ด๋ฏธ ์ฒดํฌํ–ˆ๋‹ค๋ฉด, ํ›„์† ๊ณ„์‚ฐ์„ ํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ ๋ฐ˜ํ™˜
9+
if checked in memo:
10+
return memo[checked]
11+
12+
for word in wordDict:
13+
# ์Šฌ๋ผ์ด์‹ฑ ๋Œ€์‹  startswith๋ฅผ ์“ฐ๋Š” ๊ฒƒ์ด ์„ฑ๋Šฅ์ƒ ์ด์ ์ด ์žˆ๋‹ค
14+
# ์ง€๊ธˆ ๋ณด๋ ค๋Š” ๋‹จ์–ด๊ฐ€ ๋ฌธ์ž์—ด์˜ prefix์ธ ๊ฒฝ์šฐ, ์ฆ‰ ๋‹ค์Œ ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•ด ๋ณผ ์—ฌ๊ฑด์ด ๋˜๋Š” ๊ฒฝ์šฐ
15+
# ์—ฌ๊ธฐ์„œ ์‹œ์ž‘ํ•ด์„œ ๋๊นŒ์ง€ ๊ฐ”์„ ๋•Œ ๋ฌธ์žฅ์ด ์™„์„ฑ์ด ๋˜๋‹ˆ? ๋ผ๋Š” ๊ฒƒ
16+
17+
# ๋งŒ์•ฝ ๊ฐ€๋Šฅํ•  ๊ฒฝ์šฐ, ๊ฑฐ์ณ์˜จ ๋ชจ๋“  path์— ๋Œ€ํ•ด memo ๋”•์…”๋„ˆ๋ฆฌ์—๋Š” True๊ฐ€ ์ €์žฅ๋˜๊ฒŒ ๋œ๋‹ค.
18+
# ๋˜ํ•œ early return์„ ํ†ตํ•ด ํ›„์† ์ผ€์ด์Šค๋ฅผ ๊ณ„์‚ฐํ•˜์ง€ ์•Š๋Š”๋‹ค.
19+
if s.startswith(word, checked):
20+
if self.traverse(s, wordDict, checked + len(word), memo):
21+
memo[checked] = True
22+
return True
23+
24+
# ์œ„์˜ for๋ฌธ์—์„œ ๋งŒ์กฑํ•˜๋Š” ๊ฒŒ ์—†๋‹ค๋ฉด, ์—ฌ๊ธฐ์„œ ์‹œ์ž‘ํ•ด๊ฐ€์ง€๊ณ ์„œ๋Š” ๋๊นŒ์ง€ ๊ฐˆ ์ˆ˜ ์—†๋‹ค๋Š” ๊ฒƒ
25+
memo[checked] = False
26+
return False
27+
28+
29+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
30+
memo = {}
31+
32+
return self.traverse(s, wordDict, 0, memo)

0 commit comments

Comments
ย (0)