forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_139.java
103 lines (91 loc) · 3.18 KB
/
_139.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.fishercoder.solutions;
import java.util.List;
/**
* 139. Word Break
*
* 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.
* You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings).
Please reload the code definition to get the latest changes.
*/
public class _139 {
public static class Solution1 {
/** this beats 70.46% submission. */
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
}
public static class Solution2 {
/**
* Added pruning.
* this beats 89.91% submissions.
*/
public boolean wordBreak(String s, List<String> wordDict) {
int maxLen = Integer.MIN_VALUE;
for (String word : wordDict) {
maxLen = (word.length() > maxLen) ? word.length() : maxLen;
}
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if ((i - j) > maxLen) {
continue;
}
if (dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
}
public static class Solution3 {
/**
* Added pruning, plus start from the end to check.
* This beats 95.20% submissions.
*/
public boolean wordBreak(String s, List<String> wordDict) {
int maxLen = Integer.MIN_VALUE;
for (String word : wordDict) {
maxLen = (word.length() > maxLen) ? word.length() : maxLen;
}
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int lastWordLength = 1; lastWordLength <= i && lastWordLength <= maxLen;
lastWordLength++) {
if (!dp[i - lastWordLength]) {
continue;
}
String sub = s.substring(i - lastWordLength, i);
if (wordDict.contains(sub)) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
}
}