Created
June 18, 2018 17:34
-
-
Save DonKeyHot1/606db0b36a383973630b0ce88dc071a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
public class Dictionary implements IDictionary { | |
private Node root = new Node(); | |
private static class Node { | |
Map<Character, Node> children = new HashMap<>(); | |
Node parent = null; | |
String value = null; | |
} | |
@Override | |
public boolean put(String key, String value) { | |
try { | |
Node currentNode = root; | |
Node currentParent; | |
for(char character : key.toCharArray()) { | |
if (!currentNode.children.containsKey(character)) { | |
currentNode.children.put(character, new Node()); | |
} | |
currentParent = currentNode; | |
currentNode = currentNode.children.get(character); | |
currentNode.parent = currentParent; | |
} | |
currentNode.value = value; | |
return true; | |
} catch (Exception e) { | |
System.out.println("Добавление не удалось. Причина: " + e.getMessage()); | |
return false; | |
} | |
} | |
@Override | |
public String get(String key) { | |
Node currentNode = root; | |
for (char character : key.toCharArray()) { | |
if (!currentNode.children.containsKey(character)) { | |
return null; | |
} else { | |
currentNode = currentNode.children.get(character); | |
} | |
} | |
return currentNode.value; | |
} | |
@Override | |
public boolean remove(String key) { | |
try { | |
Node currentNode = root; | |
for (char character : key.toCharArray()) { | |
if (!currentNode.children.containsKey(character)) { | |
return false; | |
} else { | |
currentNode = currentNode.children.get(character); | |
} | |
} | |
currentNode.value = null; | |
while (currentNode.parent != null && currentNode.children.size() == 0) { | |
Node currentParent = currentNode.parent; | |
if (currentParent.children.size() == 1 && currentNode.value == null) { | |
currentParent.children.clear(); | |
currentNode = currentParent; | |
} | |
else { | |
break; | |
} | |
} | |
return true; | |
} catch (Exception e) { | |
System.out.println("Удаление не удалось. Причина: " + e.getMessage()); | |
return false; | |
} | |
} | |
@Override | |
public boolean isEmpty() { | |
return root.children.isEmpty(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment