Skip to content

Commit 01e0bae

Browse files
committed
feat: implement word break solution to determine if a string can be segmented into words from a dictionary
1 parent e5cb040 commit 01e0bae

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
3+
"""
4+
์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด s๋ฅผ ๋‹จ์–ด ์‚ฌ์ „ wordDict์˜ ๋‹จ์–ด๋“ค๋กœ ๋ถ„ํ• ํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•˜๋Š” ํ•จ์ˆ˜.
5+
N์€ ๋ฌธ์ž์—ด s์˜ ๊ธธ์ด, M์€ ๋‹จ์–ด ์‚ฌ์ „์˜ ์ตœ๋Œ€ ๋‹จ์–ด ๊ธธ์ด๋กœ ๊ฐ€์ •ํ•  ๋•Œ,
6+
์‹œ๊ฐ„ ๋ณต์žก๋„: O(N * M)
7+
๊ณต๊ฐ„ ๋ณต์žก๋„: O(N)
8+
9+
Args:
10+
s (str): ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด
11+
wordDict (list[str]): ์‚ฌ์šฉ๊ฐ€๋Šฅํ•œ ๋‹จ์–ด ์‚ฌ์ „
12+
13+
Returns:
14+
bool: ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์„ ๋‹จ์–ด ์‚ฌ์ „์˜ ๋‹จ์–ด๋“ค๋กœ ๋ถ„ํ• ํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์—ฌ๋ถ€
15+
"""
16+
word_check = [False] * (len(s) + 1)
17+
max_len = len(max(wordDict, key=len))
18+
word_check[0] = True
19+
for i in range(len(s)):
20+
if not word_check[i]:
21+
continue
22+
for j in range(i + 1, min(len(s), i + max_len) + 1):
23+
# i๊นŒ์ง€์˜ ๋‹จ์–ด๊ฐ€ ์‚ฌ์ „์— ์žˆ๊ณ , i๋ถ€ํ„ฐ j๊นŒ์ง€์˜ ๋‹จ์–ด๊ฐ€ ์‚ฌ์ „์— ์žˆ์œผ๋ฉด ๋ชจ๋“  ๋‹จ์–ด๊ฐ€ ์‚ฌ์ „์— ์žˆ๋Š” ์ƒํƒœ๋กœ ํŒ๋‹จ
24+
if word_check[i] and s[i:j] in wordDict:
25+
word_check[j] = True
26+
return word_check[-1]

0 commit comments

Comments
ย (0)