mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0139.单词拆分.md
This commit is contained in:
@ -337,10 +337,53 @@ class Solution {
|
|||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
回溯
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def backtracking(self, s: str, wordSet: set[str], startIndex: int) -> bool:
|
||||||
|
# 边界情况:已经遍历到字符串末尾,返回True
|
||||||
|
if startIndex >= len(s):
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 遍历所有可能的拆分位置
|
||||||
|
for i in range(startIndex, len(s)):
|
||||||
|
word = s[startIndex:i + 1] # 截取子串
|
||||||
|
if word in wordSet and self.backtracking(s, wordSet, i + 1):
|
||||||
|
# 如果截取的子串在字典中,并且后续部分也可以被拆分成单词,返回True
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 无法进行有效拆分,返回False
|
||||||
|
return False
|
||||||
|
|
||||||
|
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
|
||||||
|
wordSet = set(wordDict) # 转换为哈希集合,提高查找效率
|
||||||
|
return self.backtracking(s, wordSet, 0)
|
||||||
|
|
||||||
|
```
|
||||||
|
DP(版本一)
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
|
||||||
|
wordSet = set(wordDict)
|
||||||
|
n = len(s)
|
||||||
|
dp = [False] * (n + 1) # dp[i] 表示字符串的前 i 个字符是否可以被拆分成单词
|
||||||
|
dp[0] = True # 初始状态,空字符串可以被拆分成单词
|
||||||
|
|
||||||
|
for i in range(1, n + 1):
|
||||||
|
for j in range(i):
|
||||||
|
if dp[j] and s[j:i] in wordSet:
|
||||||
|
dp[i] = True # 如果 s[0:j] 可以被拆分成单词,并且 s[j:i] 在单词集合中存在,则 s[0:i] 可以被拆分成单词
|
||||||
|
break
|
||||||
|
|
||||||
|
return dp[n]
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
DP(版本二)
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
|
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
|
||||||
'''排列'''
|
|
||||||
dp = [False]*(len(s) + 1)
|
dp = [False]*(len(s) + 1)
|
||||||
dp[0] = True
|
dp[0] = True
|
||||||
# 遍历背包
|
# 遍历背包
|
||||||
@ -351,17 +394,6 @@ class Solution:
|
|||||||
dp[j] = dp[j] or (dp[j - len(word)] and word == s[j - len(word):j])
|
dp[j] = dp[j] or (dp[j - len(word)] and word == s[j - len(word):j])
|
||||||
return dp[len(s)]
|
return dp[len(s)]
|
||||||
```
|
```
|
||||||
```python
|
|
||||||
class Solution: # 和视频中写法一致(和最上面C++写法一致)
|
|
||||||
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
|
|
||||||
dp = [False]*(len(s)+1)
|
|
||||||
dp[0]=True
|
|
||||||
for j in range(1,len(s)+1):
|
|
||||||
for i in range(j):
|
|
||||||
word = s[i:j]
|
|
||||||
if word in wordDict and dp[i]: dp[j]=True
|
|
||||||
return dp[-1]
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user