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
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
这是一道动态规划的题,可以先建立一个list,然后循环遍历。
比如example3中,建立数组[True, False, False, False, False, False, False, False, False, False]
第一次循环后,因为cat和cats都在wordDict中,所以数组变为[True, False, False, True, True, False, False, False, False, False]
第二次循环后,cat后面可以接sand,cats后面可以接and,所以数组变为
[True, False, False, True, True, False, False, True, False, False](两种方式都是以'd'为结尾,所以只有一个变为True)
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False for i in range(len(s)+1)]
dp[0] = True
for i in range(1,len(s)+1):
for word in wordDict:
if word == s[i-1:i+len(word)-1] and dp[i-1]:
dp[i+len(word)-1]=True
return dp[-1]
字符串分割算法

本文探讨了一种使用动态规划解决字符串分割问题的方法,通过遍历和匹配字典中的单词,判断一个给定的非空字符串是否能被分割成一个或多个字典中存在的单词序列。通过实例演示了算法的工作原理。
1575

被折叠的 条评论
为什么被折叠?



