Skip to content

Commit e1274bc

Browse files
author
weiy
committed
word break medium
1 parent 0d8e3f6 commit e1274bc

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

DP/WordBreak.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
"""
2+
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.
3+
4+
Note:
5+
6+
The same word in the dictionary may be reused multiple times in the segmentation.
7+
You may assume the dictionary does not contain duplicate words.
8+
Example 1:
9+
10+
Input: s = "leetcode", wordDict = ["leet", "code"]
11+
Output: true
12+
Explanation: Return true because "leetcode" can be segmented as "leet code".
13+
Example 2:
14+
15+
Input: s = "applepenapple", wordDict = ["apple", "pen"]
16+
Output: true
17+
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
18+
Note that you are allowed to reuse a dictionary word.
19+
Example 3:
20+
21+
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
22+
Output: false
23+
24+
给一个非空字符串和一个包含单词的非空字典。判断是否能用字典里的单词组合成给定的字符串。
25+
26+
思路:
27+
Dp:
28+
从0开始,若此分隔存在于给定字典中,则可以断开。
29+
30+
s = "leetcode", wordDict = ["leet", "code"]
31+
32+
leetcode
33+
l e e t c o d e
34+
T F F F F F F F F
35+
36+
leet
37+
s[0:0+4] in wordDict
38+
39+
s[0+4] = True
40+
41+
l e e t c o d e
42+
T F F F T F F F F
43+
当搜索到这里时会再次进行重复的搜索。
44+
45+
46+
---
47+
emmm, 写法待改进。
48+
这个写法思路一样,不过效率会低。
49+
50+
beat 3%.
51+
52+
测试地址:
53+
https://leetcode.com/problems/word-break/description/
54+
55+
"""
56+
class Solution(object):
57+
def wordBreak(self, s, wordDict):
58+
"""
59+
:type s: str
60+
:type wordDict: List[str]
61+
:rtype: bool
62+
"""
63+
64+
dp = [True] + [False] * len(s)
65+
66+
for i in range(len(s)):
67+
for j in range(i+1):
68+
if dp[j] == True:
69+
for x in wordDict:
70+
if x == s[j:j+len(x)]:
71+
dp[j+len(x)] = True
72+
73+
return dp[-1]

0 commit comments

Comments
 (0)