Skip to content

Commit 8cff5f9

Browse files
committed
- Word Break #271
1 parent a95be06 commit 8cff5f9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

word-break/ayosecu.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n^2), n = len(s)
6+
- Space Complexity: O(n + m)
7+
- n = len(s) = dp size
8+
- m = The number of characters in wordDict (wordDict size)
9+
"""
10+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
11+
n = len(s)
12+
wordDict = set(wordDict)
13+
14+
# Use DP: dp[i] => s[0:i] is possible to be seperated by dictionary words
15+
dp = [False] * (n + 1)
16+
dp[0] = True
17+
18+
for i in range(1, n + 1):
19+
for j in range(i):
20+
if dp[j] and s[j:i] in wordDict:
21+
dp[i] = True
22+
break # s[i-1] is possible => don't need to check forward string
23+
24+
return dp[-1] # check s[0:n]
25+
26+
tc = [
27+
("leetcode", ["leet","code"], True),
28+
("applepenapple", ["apple","pen"], True),
29+
("catsandog", ["cats","dog","sand","and","cat"], False)
30+
]
31+
32+
sol = Solution()
33+
for i, (s, wordDict, e) in enumerate(tc, 1):
34+
r = sol.wordBreak(s, wordDict)
35+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)