Skip to content

Instantly share code, notes, and snippets.

@sbilello
Created August 11, 2017 22:56
Show Gist options
  • Save sbilello/76a61ae45487edf516f559f9f40b0e8d to your computer and use it in GitHub Desktop.
Save sbilello/76a61ae45487edf516f559f9f40b0e8d to your computer and use it in GitHub Desktop.
Tries.java
public class Tries {
public static void main(String[] args) {
Node n = new Node();
n.add("ciao");
n.add("ciaone");
n.printWords();
System.out.println();
n.delete("ciaone");
System.out.println();
n.printWords();
}
public static class Node {
Map<Character, Node> children = new HashMap<>();
boolean stopWord = false;
public void add(String input) {
add(input, 0);
}
private void add(String input, int index) {
Character c = input.charAt(index);
Node child;
if (children.containsKey(c)) {
child = children.get(c);
} else {
child = new Node();
children.put(c, child);
}
if (index == input.length() - 1) {
stopWord = true;
return;
}
child.add(input, index + 1);
}
public boolean search(String search) {
return search(search, 0);
}
private boolean search(String search, int index) {
if (index == search.length()) {
return false;
}
if (children.containsKey(search.charAt(index))) {
if (index == search.length() - 1 && stopWord) {
return true;
}
return children.get(search.charAt(index)).search(search, index + 1);
} else {
return false;
}
}
public void delete(String delete) {
if (search(delete)) {
delete(delete, 0);
}
}
private boolean delete(String delete, int i) {
if (delete.length() - 1 == i) {
if (!stopWord) {
return false;
}
children.remove(delete.charAt(i));
return children.size() == 0;
}
char ch = delete.charAt(i);
Node child = children.get(ch);
if (child == null) {
return false;
}
boolean shouldDelete = child.delete(delete, i + 1);
if (shouldDelete && !stopWord) {
children.remove(ch);
return children.size() == 0;
}
return false;
}
public void printWords() {
List<String> words = new LinkedList<>();
print(new StringBuilder(), words);
for (String s : words) {
System.out.println(s);
}
}
public void print(StringBuilder sb, List<String> words) {
for (Character c : children.keySet()) {
sb.append(c);
if (stopWord) {
words.add(sb.toString());
}
Node child = children.get(c);
child.print(sb, words);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment