Skip to content

Instantly share code, notes, and snippets.

@iain17
Created September 28, 2017 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iain17/e9f6898d930355a1454a52ad86c330a8 to your computer and use it in GitHub Desktop.
Save iain17/e9f6898d930355a1454a52ad86c330a8 to your computer and use it in GitHub Desktop.
Hackerrank contacts problem
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static class Node {
public Character value;
private HashMap<Character, Node> children = new HashMap<Character, Node>();
public boolean isCompleteWord;
//To speed up the countCompletedWords
public int numWords = 0;
Node(Character value, boolean isCompleteWord) {
this.value = value;
this.isCompleteWord = isCompleteWord;
}
public Node putChild(Character letter, boolean isCompleteWord) {
Node node = new Node(letter, isCompleteWord);
children.put(letter, node);
return node;
}
public Node getChild(Character letter) {
return children.get(letter);
}
/*
too slow...
public int countCompletedWords() {
int total = 0;
for(Map.Entry<Character, Node> entry : children.entrySet()) {
total += entry.getValue().countCompletedWords();
}
if(this.isCompleteWord) {
total++;
}
return total;
}
*/
public int countCompletedWords() {
return numWords;
}
public String toString() {
String result = this.value + "("+this.numWords+"):{\n";
for(Map.Entry<Character, Node> entry : children.entrySet()) {
result += "\t" + entry.getValue().toString();
}
result += "}\n";
return result;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Node root = new Node('*', false);
for(int a0 = 0; a0 < n; a0++){
String op = in.next();
String contact = in.next();
if(op.equals("add")) {
add(root, contact);
}
if(op.equals("find")) {
//System.out.println(root.toString());
System.out.println(find(root, contact));
}
}
}
public static void add(Node root, String word) {
Node currentNode = root;
for(int i = 0; i < word.length(); i++) {
Character letter = word.charAt(i);
Node existingLetterNode = currentNode.getChild(letter);
if(existingLetterNode != null) {
currentNode = existingLetterNode;
currentNode.numWords++;
continue;
}
currentNode = currentNode.putChild(letter, false);
currentNode.numWords++;
}
currentNode.putChild('*', true);
}
public static int find(Node root, String word) {
Node currentNode = root;
for(int i = 0; i < word.length(); i++) {
Character letter = word.charAt(i);
currentNode = currentNode.getChild(letter);
if(currentNode == null) {
break;
}
}
if(currentNode == null) {
return 0;
}
return currentNode.countCompletedWords();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment