šØ Word Break (#139)
š Problem Linkā
š Problem Statementā
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.
š” Examplesā
Example 1ā
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Example 2ā
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Example 3ā
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
š Key Insights & Approachā
Core Observation: dp[i] = true if substring [0...i] can be segmented using wordDict.
Why DP?
- O(n² * m) time where m = avg word length
- O(n) space
- Check all possible word breaks
Pattern: "String Segmentation DP" pattern.
š Solution: Pythonā
Approach: Bottom-Up DPā
Time Complexity: O(n² * m) | Space Complexity: O(n)
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
word_set = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break
return dp[len(s)]
šµ Solution: Golangā
Approach: DPā
Time Complexity: O(n² * m) | Space Complexity: O(n)
func wordBreak(s string, wordDict []string) bool {
wordSet := make(map[string]bool)
for _, word := range wordDict {
wordSet[word] = true
}
dp := make([]bool, len(s)+1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}