Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d8c51b2

Browse files
Update 0139.单词拆分.md
1 parent 45037ce commit d8c51b2

File tree

1 file changed

+44
-12
lines changed

1 file changed

+44
-12
lines changed

‎problems/0139.单词拆分.md‎

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -337,10 +337,53 @@ class Solution {
337337

338338
Python:
339339

340+
回溯
341+
```python
342+
class Solution:
343+
def backtracking(self, s: str, wordSet: set[str], startIndex: int) -> bool:
344+
# 边界情况:已经遍历到字符串末尾,返回True
345+
if startIndex >= len(s):
346+
return True
347+
348+
# 遍历所有可能的拆分位置
349+
for i in range(startIndex, len(s)):
350+
word = s[startIndex:i + 1] # 截取子串
351+
if word in wordSet and self.backtracking(s, wordSet, i + 1):
352+
# 如果截取的子串在字典中,并且后续部分也可以被拆分成单词,返回True
353+
return True
354+
355+
# 无法进行有效拆分,返回False
356+
return False
357+
358+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
359+
wordSet = set(wordDict) # 转换为哈希集合,提高查找效率
360+
return self.backtracking(s, wordSet, 0)
361+
362+
```
363+
DP(版本一)
364+
```python
365+
class Solution:
366+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
367+
wordSet = set(wordDict)
368+
n = len(s)
369+
dp = [False] * (n + 1) # dp[i] 表示字符串的前 i 个字符是否可以被拆分成单词
370+
dp[0] = True # 初始状态,空字符串可以被拆分成单词
371+
372+
for i in range(1, n + 1):
373+
for j in range(i):
374+
if dp[j] and s[j:i] in wordSet:
375+
dp[i] = True # 如果 s[0:j] 可以被拆分成单词,并且 s[j:i] 在单词集合中存在,则 s[0:i] 可以被拆分成单词
376+
break
377+
378+
return dp[n]
379+
380+
381+
```
382+
DP(版本二)
383+
340384
```python
341385
class Solution:
342386
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
343-
'''排列'''
344387
dp = [False]*(len(s) + 1)
345388
dp[0] = True
346389
# 遍历背包
@@ -351,17 +394,6 @@ class Solution:
351394
dp[j] = dp[j] or (dp[j - len(word)] and word == s[j - len(word):j])
352395
return dp[len(s)]
353396
```
354-
```python
355-
class Solution: # 和视频中写法一致(和最上面C++写法一致)
356-
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
357-
dp = [False]*(len(s)+1)
358-
dp[0]=True
359-
for j in range(1,len(s)+1):
360-
for i in range(j):
361-
word = s[i:j]
362-
if word in wordDict and dp[i]: dp[j]=True
363-
return dp[-1]
364-
```
365397

366398

367399

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /