单词拆分 给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例 1:
输入: s = “leetcode”, wordDict = [“leet”, “code”] 输出: true 解释: 返回 true
因为 “leetcode” 可以由 “leet” 和 “code” 拼接成。
博主拿到这道题的想法是把首字母和字典的首字母进行比对,如果首字母一致,便逐个遍历剩下的字母,如果完全一致,error =0进入切割,s=剩下的字符串,重新回到wordbreak这个函数里面进行切割,直到s为空
貌似看起来是可以的,但是会出现回溯的时候,把return的值更新掉了,导致返回结果不正确
from typing import List
class Solution:
def __init__(self):
Val = 0
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
index = 0
error = 0
for word in range(len(wordDict)): #第几个词
if s[index] == wordDict[word][index]:
for i in range(1,len(wordDict[word])):
if s[i] != wordDict[word][i]:
error = 1
break
if error == 0:
s = s[len(wordDict[word]):]
if s == "" :
self.Val = 1
return True
else :
self.wordBreak(s, wordDict)
if self.Val == 1:
return True
else:
return False
if __name__ == "__main__":
s = "leetcode"
wordDict = ["code", "leet"]
result = Solution()
print(result.wordBreak(s,wordDict))
应该是创建一个列表,当我的第 [i, j]个字符串的长度如果能够在字典中找得到,返回True,如果说j是字符串的长度,并且第0-i个字符串都为True,则最终的结果返回的是True。
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [False for _ in range(len(s) + 1)] #初始化一个布尔逻辑False数组,这个数组的长度为字符串长度加1
maxlen = max([len(word) for word in wordDict]) #最大长度为word列表里最长的
dp[0] = True #初始化第一个为Ture
for i in range(1, len(s) + 1): #遍历字符串中的每一个字符
for j in range(max(0, i - maxlen), i): #这个没想懂?
if dp[j] and s[j:i] in wordDict:
dp[i] = True
return dp[len(s)]
if __name__ == "__main__":
s = "leetcode"
wordDict = ["code", "leet","codelist"]
result = Solution()
print(result.wordBreak(s,wordDict))