Refactor Trie (#3469)

This commit is contained in:
Grzegorz Piwowarek 2018-01-20 15:05:41 +01:00 committed by GitHub
parent d64468eddc
commit 7bd1fbf734
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -9,26 +9,23 @@ public class Trie {
public void insert(String word) { public void insert(String word) {
TrieNode current = root; TrieNode current = root;
for (int i = 0; i < word.length(); i++) { for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i); current = current.getChildren().computeIfAbsent(word.charAt(i), c -> new TrieNode());
TrieNode node = current.getChildren()
.get(ch);
if (node == null) {
node = new TrieNode();
current.getChildren()
.put(ch, node);
}
current = node;
} }
current.setEndOfWord(true); current.setEndOfWord(true);
} }
public boolean find(String word) { public boolean delete(String word) {
return delete(root, word, 0);
}
public boolean containsNode(String word) {
TrieNode current = root; TrieNode current = root;
for (int i = 0; i < word.length(); i++) { for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i); char ch = word.charAt(i);
TrieNode node = current.getChildren() TrieNode node = current.getChildren().get(ch);
.get(ch);
if (node == null) { if (node == null) {
return false; return false;
} }
@ -37,8 +34,8 @@ public class Trie {
return current.isEndOfWord(); return current.isEndOfWord();
} }
public void delete(String word) { public boolean isEmpty() {
delete(root, word, 0); return root == null;
} }
private boolean delete(TrieNode current, String word, int index) { private boolean delete(TrieNode current, String word, int index) {
@ -47,30 +44,19 @@ public class Trie {
return false; return false;
} }
current.setEndOfWord(false); current.setEndOfWord(false);
return current.getChildren() return current.getChildren().isEmpty();
.size() == 0;
} }
char ch = word.charAt(index); char ch = word.charAt(index);
TrieNode node = current.getChildren() TrieNode node = current.getChildren().get(ch);
.get(ch);
if (node == null) { if (node == null) {
return false; return false;
} }
boolean shouldDeleteCurrentNode = delete(node, word, index + 1); boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
if (shouldDeleteCurrentNode) { if (shouldDeleteCurrentNode) {
current.getChildren() current.getChildren().remove(ch);
.remove(ch);
return current.getChildren().isEmpty(); return current.getChildren().isEmpty();
} }
return false; return false;
} }
public boolean containsNode(String word) {
return find(word);
}
public boolean isEmpty() {
return root == null;
}
} }