139. Word Break
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Author: Huahua # Time complexity: O(n^2) # Space complexity: O(n^2) class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: words = set(wordDict) n = len(s) @cache def dp(s: str) -> bool: """Returns whether s is breakable.""" if not s: return True for l in range(1, min(n, 20) + 1): if s[0:l] in words and dp(s[l:]): return True return dp(s) |
Optimization
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Author: Huahua # Time complexity: O(n*l^2) # Space complexity: O(n) class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: words = set(wordDict) n = len(s) @cache def dp(i: int) -> bool: """Returns whether s[i:] is breakable.""" if i >= n: return True for l in range(1, min(n, 20) + 1): if s[i:i+l] in words and dp(i + l): return True return dp(0) |