|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/word-break/ |
| 3 | +
|
| 4 | +Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a |
| 5 | +space-separated sequence of one or more dictionary words. |
| 6 | +Note that the same word in the dictionary may be reused multiple times in the segmentation. |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +Input: s = "leetcode", wordDict = ["leet","code"] |
| 10 | +Output: true |
| 11 | +Explanation: Return true because "leetcode" can be segmented as "leet code". |
| 12 | +
|
| 13 | +Example 2: |
| 14 | +Input: s = "applepenapple", wordDict = ["apple","pen"] |
| 15 | +Output: true |
| 16 | +Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". |
| 17 | +Note that you are allowed to reuse a dictionary word. |
| 18 | +
|
| 19 | +Example 3: |
| 20 | +Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] |
| 21 | +Output: false |
| 22 | + |
| 23 | +Constraints: |
| 24 | +1 <= s.length <= 300 |
| 25 | +1 <= wordDict.length <= 1000 |
| 26 | +1 <= wordDict[i].length <= 20 |
| 27 | +s and wordDict[i] consist of only lowercase English letters. |
| 28 | +All the strings of wordDict are unique. |
| 29 | +""" |
| 30 | +# TLE - O (2^N) |
| 31 | +class Solution: |
| 32 | + def wordBreak(self, s: str, wordDict: List[str]) -> bool: |
| 33 | + return self.helper(s, set(wordDict)) |
| 34 | + |
| 35 | + def helper(self, s, words): |
| 36 | + if not s: |
| 37 | + return True |
| 38 | + |
| 39 | + for index in range(1, len(s)+1): |
| 40 | + if s[:index] in words and self.helper(s[index:], words): |
| 41 | + return True |
| 42 | + return False |
0 commit comments