Skip to content

Instantly share code, notes, and snippets.

@deque-blog
Created March 6, 2020 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deque-blog/5fe82f9d346428ce2bfe08cae2f5e641 to your computer and use it in GitHub Desktop.
Save deque-blog/5fe82f9d346428ce2bfe08cae2f5e641 to your computer and use it in GitHub Desktop.
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
if not wordDict:
return False
word_dict = set(wordDict)
smallest_word = min(len(w) for w in wordDict)
longest_word = max(len(w) for w in wordDict)
@lru_cache(maxsize=None)
def can_break_from(i: int) -> bool:
if i == len(s):
return True
for delta in range(smallest_word, longest_word+1):
if s[i:i+delta] in word_dict:
if can_break_from(i+delta):
return True
return False
return can_break_from(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment