Leetcode 139.单词拆分
1 题目描述(Leetcode题目链接)
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
- 拆分时可以重复使用字典中的单词。
- 你可以假设字典中没有重复的单词。
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
2 题解
动态规划问题,定义 D P [ i ] DP[i] DP[i]表示从第一个字母到第 i i i个字母能否被拆分,0代表否,1代表能。遍历到第 i i i个字母时, D P [ i ] DP[i] DP[i]的取值根据 D P [ 0 ] DP[0] DP[0]到 D P [ i − 1 ] DP[i-1] DP[i−1]来判断,如果 D P [ j ] = 1 DP[j]=1 DP[j]=1,且 j j j到 i i i组成的单词在表里,那么 D P [ i ] = 1 DP[i]=1 DP[i]=1
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
length = len(s)+1
wordSet = set(wordDict)
dp = [0]*length
dp[0] = 1
for i in range(1, length):
for j in range(i+1):
if dp[j] == 1 and s[j:i] in wordSet:
dp[i] = 1
break
return dp[-1] == 1