Skip to content

Commit 222ba96

Browse files
committed
Word Break
1 parent 67b1117 commit 222ba96

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

word-break/forest000014.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
3+
Time Complexity: O(s * L^2)
4+
- L is max length of wordDict[i]
5+
Space Complexity: O(s + w * L)
6+
*/
7+
class Solution {
8+
public boolean wordBreak(String s, List<String> wordDict) {
9+
Set<String> wordSet = new HashSet<>();
10+
int maxLen = 0;
11+
for (String word : wordDict) {
12+
wordSet.add(word);
13+
maxLen = Math.max(maxLen, word.length());
14+
}
15+
16+
boolean[] dp = new boolean[s.length() + 1];
17+
dp[0] = true;
18+
19+
for (int i = 0; i < s.length(); i++) {
20+
for (int j = 1; j <= maxLen; j++) {
21+
int beginIdx = i - j + 1;
22+
if (beginIdx < 0)
23+
continue;
24+
if (wordSet.contains(s.substring(beginIdx, i + 1)) && dp[beginIdx]) {
25+
dp[i + 1] = true;
26+
break;
27+
}
28+
}
29+
}
30+
31+
return dp[s.length()];
32+
}
33+
}

0 commit comments

Comments
 (0)