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 6cf4f61

Browse files
Merge pull request youngyangyang04#1643 from zhicheng-lee/zhicheng-lee-patch-11
更新 0139.单词拆分.md Java代码
2 parents 8431f5a + cf51b7c commit 6cf4f61

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

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

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,11 +234,13 @@ Java:
234234
```java
235235
class Solution {
236236
public boolean wordBreak(String s, List<String> wordDict) {
237+
HashSet<String> set = new HashSet<>(wordDict);
237238
boolean[] valid = new boolean[s.length() + 1];
238239
valid[0] = true;
240+
239241
for (int i = 1; i <= s.length(); i++) {
240-
for (int j = 0; j < i; j++) {
241-
if (wordDict.contains(s.substring(j,i)) && valid[j]) {
242+
for (int j = 0; j < i&&!valid[i]; j++) {
243+
if (set.contains(s.substring(j,i)) && valid[j]) {
242244
valid[i] = true;
243245
}
244246
}
@@ -248,6 +250,26 @@ class Solution {
248250
}
249251
}
250252

253+
// 另一种思路的背包算法
254+
class Solution {
255+
public boolean wordBreak(String s, List<String> wordDict) {
256+
boolean[] dp = new boolean[s.length() + 1];
257+
dp[0] = true;
258+
259+
for (int i = 1; i <= s.length(); i++) {
260+
for (String word : wordDict) {
261+
int len = word.length();
262+
if (i >= len && dp[i - len] && word.equals(s.substring(i - len, i))) {
263+
dp[i] = true;
264+
break;
265+
}
266+
}
267+
}
268+
269+
return dp[s.length()];
270+
}
271+
}
272+
251273
// 回溯法+记忆化
252274
class Solution {
253275
private Set<String> set;
@@ -285,7 +307,7 @@ class Solution {
285307

286308
Python:
287309

288-
```python3
310+
```python
289311
class Solution:
290312
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
291313
'''排列'''

0 commit comments

Comments
(0)

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