题目描述:
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,一个列表wordDict,wordDict中的元素也是字符串,现在开始分割s,问你,分割方式不限,能否在wordDict中找到,也就是匹配出分割后的s
- 看完三个example,应该也都明白了
解题思路:
- 声明:此题为动态规划标签下的题目,下面上动态规划解法思路
- Step1:确定dp table 的含义,每个dp[i]的数值代表啥意思,依题意,本人这样定义,dp[i]的True or False 代表以第i个元素结尾时的子字符串s,能否分割成wordDict中的元素,能,True,否,False
- Step2:找出如何由dp[i-1]能够以某种方式或者式子推出dp[i]的值呢,因为在第i个元素的位置时,从0-i这个子字符串到底能否在wordDict中找出来,要么,0-i子串,直接在wordDict中,要么就是第0 - i-1这个子串在wordDict中,而且i这个字符也在,按照这种规则,0 - i-2, i-1 - i,也同样如此,没有别的可能
- Step3:编程实现想法,即填充dp table。你怎么知道0 - i-1到底可不可以在wordDict中找出来呢?也就是dp[i-1]为True。不要忘了,你的dp table就是这样定义的啊!!!
少废话,上代码:
class Solution:
def wordBreak(self, s, wordDict):
# 定义dp table,初始化全为False
dp = [False] * len(s)
# 在最开头插入一个元素True
# 保证从s的第一个元素开始,按照同样的逻辑
# 可以一次循环下去
dp.insert(0, True)
# 外层i循环匹配dp table的1号元素-末尾元素
for i in range(1, len(s)+1):
# 内层循环j匹配s中元素的索引
for j in range(i):
# 递推关系
# 到第j个元素为止,能否在wordDict中查找到
# 只有如下满足如下这种关系,才可能为True
# 也就是找到
if dp[j] and s[j:i] in wordDict:
dp[i] = True
return dp[-1] # 返回dp table最后一个元素,即为答案
运行时间和内存占用:
- Runtime: 36 ms, faster than 80.31% of Python3 online submissions for Word Break
- Memory Usage: 14 MB, less than 5.55% of Python3 online submissions for Word Break.