Skip to content

Commit a07ef04

Browse files
committed
Word Break
1 parent 91dd3d2 commit a07ef04

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leetcode.medium;
2+
3+
import java.util.*;
4+
5+
public class WordBreak {
6+
7+
boolean wordBreak(String s, java.util.List<String> wordDict) {
8+
9+
// Convert the dictionary to a set for O(1) lookups
10+
Set<String> wordSet = new HashSet<>(wordDict);
11+
12+
// Find the maximum word length in the dictionary
13+
int maxLen = 0;
14+
for (String word : wordDict) {
15+
maxLen = Math.max(maxLen, word.length());
16+
}
17+
18+
int n = s.length();
19+
// dp[i] states if the substring s[0..i] can be segmented
20+
boolean[] dp = new boolean[n + 1];
21+
22+
// Base case: empty string is valid
23+
dp[0] = true;
24+
25+
for (int i = 1; i <= n; i++) {
26+
27+
// Check prefixes of length up to maxLen
28+
for (int j = i - 1; j >= Math.max(0, i - maxLen); j--) {
29+
if (dp[j] && wordSet.contains(s.substring(j, i))) {
30+
dp[i] = true;
31+
break; // No need to check further prefixes
32+
}
33+
}
34+
35+
}
36+
37+
return dp[n];
38+
}
39+
40+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package leetcode.medium;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class WordBreakTest {
8+
9+
private final WordBreak wordBreak;
10+
11+
WordBreakTest() {
12+
wordBreak = new WordBreak();
13+
}
14+
15+
@Test
16+
void testWordBreak1() {
17+
assertTrue(wordBreak.wordBreak("studyalgorithms", java.util.List.of("study", "algorithms")));
18+
}
19+
20+
@Test
21+
void testWordBreak2() {
22+
assertTrue(wordBreak.wordBreak("applepenapple", java.util.List.of("apple", "pen")));
23+
}
24+
25+
@Test
26+
void testWordBreak3() {
27+
assertFalse(wordBreak.wordBreak("catsandog", java.util.List.of("cats", "dog", "sand", "and", "cat")));
28+
}
29+
30+
@Test
31+
void testWordBreak4() {
32+
assertTrue(wordBreak.wordBreak("aaaaaaa", java.util.List.of("aaaa", "aaa")));
33+
}
34+
35+
@Test
36+
void testWordBreak5() {
37+
assertFalse(wordBreak.wordBreak("aaaaa", java.util.List.of("aaaa", "aaa")));
38+
}
39+
}

0 commit comments

Comments
 (0)