-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathWordBreak.java
More file actions
78 lines (54 loc) · 1.57 KB
/
Copy pathWordBreak.java
File metadata and controls
78 lines (54 loc) · 1.57 KB
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
class Node {
private Map<Character, Node> children = new HashMap<>();
private boolean isWord;
public Map<Character, Node> getChildren() {
return children;
}
public void setEndOfWord(boolean isWord) {
this.isWord = isWord;
}
public boolean isEndOfWord() {
return isWord;
}
}
class Trie {
private Node root;
public Trie() {
root = new Node();
}
public void addWord(String word) {
Node current = root;
for (char c : word.toCharArray()) {
current = current.getChildren().computeIfAbsent(c , x -> new Node());
}
current.setEndOfWord(true);
}
public boolean search(String word) {
boolean[] found = new boolean[word.length() + 1];
found[0] = true;
for (int i = 0; i < word.length(); i++) {
if (found[i]) {
Node current = root;
for (int j = i; j < word.length(); j++ ){
if (current == null) {
break;
}
current = current.getChildren().get(word.charAt(j));
if (current != null && current.isEndOfWord()) {
found[j + 1] = true;
}
}
}
}
return found[word.length()];
}
}
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Trie trie = new Trie();
for (String word : wordDict) {
trie.addWord(word);
}
return trie.search(s);
}
}