Files

75 lines
1.9 KiB
Java
Raw Permalink Normal View History

2017-02-18 23:43:07 -06:00
// Author: Rodney Shaghoulian
2018-07-27 16:45:56 -07:00
// Github: github.com/RodneyShag
// HackerRank: hackerrank.com/RodneyShag
2017-02-18 23:43:07 -06:00
import java.util.Scanner;
import java.util.HashMap;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
2017-04-26 16:15:39 -07:00
Trie trie = new Trie();
2017-04-05 18:42:35 -05:00
for (int i = 0; i < n; i++) {
String operation = scan.next();
String contact = scan.next();
if (operation.equals("add")) {
2017-04-26 16:15:39 -07:00
trie.add(contact);
2017-04-05 18:42:35 -05:00
} else if (operation.equals("find")) {
2017-04-26 16:15:39 -07:00
System.out.println(trie.find(contact));
2017-02-18 23:43:07 -06:00
}
}
scan.close();
}
2017-04-26 16:15:39 -07:00
}
2017-04-05 18:42:35 -05:00
2017-04-26 16:15:39 -07:00
/* Based loosely on tutorial video in this problem */
class TrieNode {
private HashMap<Character, TrieNode> children = new HashMap<>();
public int size = 0; // this was the main trick to decrease runtime to pass tests.
public void putChildIfAbsent(char ch) {
children.putIfAbsent(ch, new TrieNode());
}
public TrieNode getChild(char ch) {
return children.get(ch);
}
}
class Trie {
TrieNode root = new TrieNode();
Trie(){} // default constructor
Trie(String[] words) {
for (String word : words) {
add(word);
}
}
public void add(String str) {
2017-02-18 23:43:07 -06:00
TrieNode curr = root;
for (int i = 0; i < str.length(); i++) {
Character ch = str.charAt(i);
2017-04-26 16:15:39 -07:00
curr.putChildIfAbsent(ch);
curr = curr.getChild(ch);
2017-04-05 18:42:35 -05:00
curr.size++;
2017-02-18 23:43:07 -06:00
}
}
2017-04-26 16:15:39 -07:00
public int find(String prefix) {
2017-02-18 23:43:07 -06:00
TrieNode curr = root;
/* Traverse down tree to end of our prefix */
2017-04-05 18:42:35 -05:00
for (int i = 0; i < prefix.length(); i++) {
Character ch = prefix.charAt(i);
2017-04-26 16:15:39 -07:00
curr = curr.getChild(ch);
if (curr == null) {
2017-02-18 23:43:07 -06:00
return 0;
}
}
return curr.size;
}
}