Description
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
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
Solutions
1. DP
dp[i] 表示字符串 s[:i] 能否拆分成符合要求的子字符串,如果s[j:i] 在给定的字符串组中,且 dp[j] 为 True(即字符串s[:j]能够拆分成符合要求的子字符串),那么此时 dp[i] 也就为 True 了。
# Time: O(n^2)
# Space: O(1)
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
dp = [False for _ in range(n+1)]
dp[0] = True
for i in range(1, n+1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
return dp[n]
# 36/36 cases passed (44 ms)
# Your runtime beats 62.15 % of python3 submissions
# Your memory usage beats 100 % of python3 submissions (12.9 MB)
2. 神奇做法
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# dp: f[i]:if str[0..i-1] can be break
# [0..i-1] = [0...i-j-1][i-j...i-1],check [i-j...i-1] in the dict or not
if not wordDict:
return False
n = len(s)
f = [False] * (n + 1)
f[0] = True
maxLength = max([len(w) for w in wordDict])
for i in range(1, n + 1):
for length in range(1, min(i, maxLength) + 1):
if not f[i - length]:
continue
if s[i-length:i] in wordDict:
f[i] = True
break
return f[n]
# # Using BFS:
# stack = [0]
# visited = [0] * len(s)
# while stack:
# start = stack.pop(0)
# if visited[start] == 0:
# for i in range(start+1, len(s)+1):
# if s[start:i] in wordDict:
# stack.append(i)
# if i == len(s):
# return True
# visited[start] == 1
# return False
# Using Brute Force, backtracking the search space, time exceed limit
# def backTracking(start):
# if start == len(s):
# return True
# for i in range(start+1,len(s)+1):
# if s[start:i] in wordDict and backTracking(i):
# return True
# return False
# return backTracking(0)