Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false
Constraints:
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20sandwordDict[i]consist of only lowercase English letters.- All the strings of
wordDictare unique.
ChatGPT's Solution:
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: word_set = set(wordDict) # Convert list to set to allow O(1) lookup n = len(s) dp = [False] * (n + 1) dp[0] = True # Empty string is always "breakable" for i in range(1, n + 1): for j in range(i): if dp[j] and s[j:i] in word_set: dp[i] = True break # No need to check further if s[0:i] is breakable return dp[n]

Here's the same implementation with detailed trace output that explains each step of the process:
def wordBreak(s: str, wordDict: list[str]) -> bool: word_set = set(wordDict) n = len(s) dp = [False] * (n + 1) dp[0] = True # Base case: empty string is breakable print(f"String: '{s}'") print(f"Dictionary: {wordDict}") print(f"{'i':>2} {'s[j:i]':>10} {'dp[j]':>7} {'dp[i]':>7} Explanation") for i in range(1, n + 1): for j in range(i): substring = s[j:i] if dp[j] and substring in word_set: dp[i] = True print(f"{i:>2} {substring:>10} {str(dp[j]):>7} {str(dp[i]):>7} Found '{substring}' in dict, dp[{i}] = True") break else: print(f"{i:>2} {substring:>10} {str(dp[j]):>7} {str(dp[i]):>7} ", end="") if not dp[j]: print(f"dp[{j}] is False") elif substring not in word_set: print(f"'{substring}' not in dict") print("\nFinal DP Table:", dp) return dp[n]
Example Run:
s = "applepenapple" wordDict = ["apple", "pen"] wordBreak(s, wordDict)
Sample Output:
String: 'applepenapple' Dictionary: ['apple', 'pen'] i s[j:i] dp[j] dp[i] Explanation 1 a False False dp[0] is False 2 ap False False dp[0] is False 3 app False False dp[0] is False 4 appl False False dp[0] is False 5 apple True True Found 'apple' in dict, dp[5] = True ... Final DP Table: [True, False, False, False, False, True, ..., True]

浙公网安备 33010602011771号