Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Imre Balassa
2018-08-13 21:18:36 +02:00
1974 changed files with 63806 additions and 8965 deletions

View File

@@ -1,13 +1,13 @@
package com.baeldung.trie;
public class Trie {
class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
public void insert(String word) {
void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
@@ -16,11 +16,11 @@ public class Trie {
current.setEndOfWord(true);
}
public boolean delete(String word) {
boolean delete(String word) {
return delete(root, word, 0);
}
public boolean containsNode(String word) {
boolean containsNode(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
@@ -34,7 +34,7 @@ public class Trie {
return current.isEndOfWord();
}
public boolean isEmpty() {
boolean isEmpty() {
return root == null;
}
@@ -51,7 +51,7 @@ public class Trie {
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord();
if (shouldDeleteCurrentNode) {
current.getChildren().remove(ch);

View File

@@ -4,28 +4,18 @@ import java.util.HashMap;
import java.util.Map;
class TrieNode {
private Map<Character, TrieNode> children;
private final Map<Character, TrieNode> children = new HashMap<>();
private boolean endOfWord;
public TrieNode() {
children = new HashMap<>();
endOfWord = false;
}
public Map<Character, TrieNode> getChildren() {
Map<Character, TrieNode> getChildren() {
return children;
}
public void setChildren(Map<Character, TrieNode> children) {
this.children = children;
}
public boolean isEndOfWord() {
boolean isEndOfWord() {
return endOfWord;
}
public void setEndOfWord(boolean endOfWord) {
void setEndOfWord(boolean endOfWord) {
this.endOfWord = endOfWord;
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -1,6 +1,7 @@
package com.baeldung.trie;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -53,6 +54,19 @@ public class TrieUnitTest {
assertFalse(trie.containsNode("Programming"));
}
@Test
public void givenATrie_whenDeletingOverlappingElements_thenDontDeleteSubElement() {
Trie trie1 = new Trie();
trie1.insert("pie");
trie1.insert("pies");
trie1.delete("pies");
Assertions.assertTrue(trie1.containsNode("pie"));
}
private Trie createExampleTrie() {
Trie trie = new Trie();