题:https://leetcode.com/problems/word-break/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
思路
动态规格
字符串s中,下标i。dp[i] 为位置 i 前的字符都包含在字典中。(i之前,所以在遍历i时需要到len(s))
状态转移的方程为: dp[i] = True if dp[j] and s[j:i] in wordDict ,j = 0,…,i-1
经过一次 i 遍历便可得到。
note:
1.对于 j 的遍历顺序,如果从0开始,即把 s[0:i] 从前往后切 s[0:j] 、 s[j:i],看 s[j:i] 是否在 wordDict中,由于整个s存在wordDict中比较少,会增加额外的开销。更好的方法是j从i-1到0遍历,即把s[0:i]从后往前切。
2.python 语法:
#生成 python 数组的方法:
dp = [False]*(len(s))
#生成 python 默认Dcit的方法 (查询的速度会更快)
from collections import defaultdict
def get_False():
return False
dp = defaultdict(get_False)
code
from collections import defaultdict
def get_False():
return False
class Solution:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = defaultdict(get_False)
# dp = [False]*(len(s)+1)
dp[0] = True
for i in range(1,len(s)+1):
for j in range(i-1,-1,-1):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break
return dp[len(s)]