Skip to content

Commit b53a31e

Browse files
committed
feat: word-break
1 parent 3758421 commit b53a31e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

word-break/minji-go.java

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/word-break/">week05-4.word-break</a>
3+
* <li>Description: return true if s can be segmented into a space-separated sequence of one or more dictionary words.</li>
4+
* <li>Topics: Array, Hash Table, String, Dynamic Programming, Trie, Memoization</li>
5+
* <li>Time Complexity: O(N³), Runtime 7ms </li>
6+
* <li>Space Complexity: O(N+W), Memory 44.59MB </li>
7+
*/
8+
class Solution {
9+
public boolean wordBreak(String s, List<String> wordDict) {
10+
Trie trie = new Trie();
11+
for (String str : wordDict) {
12+
trie.insert(str);
13+
}
14+
15+
List<Integer> dp = new ArrayList<>();
16+
dp.add(-1);
17+
for (int i = 0; i < s.length(); i++) {
18+
for (int j = dp.size() - 1; j >= 0; j--) {
19+
int startIndex = dp.get(j);
20+
if (trie.search(s.substring(startIndex + 1, i + 1))) {
21+
dp.add(i);
22+
break;
23+
}
24+
}
25+
}
26+
27+
return dp.contains(s.length() - 1);
28+
}
29+
30+
class Trie {
31+
private boolean end;
32+
private final Map<Character, Trie> children = new HashMap<>();
33+
34+
public void insert(String word) {
35+
Trie node = this;
36+
for (Character c : word.toCharArray()) {
37+
node = node.children.computeIfAbsent(c, k -> new Trie());
38+
}
39+
node.end = true;
40+
}
41+
42+
public boolean search(String word) {
43+
Trie node = this;
44+
for (Character c : word.toCharArray()) {
45+
node = node.children.get(c);
46+
if (node == null) {
47+
return false;
48+
}
49+
}
50+
return node.end;
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)