Created
May 1, 2019 02:00
-
-
Save MagallanesFito/2566d48c62099db29cf3f9c6f74f391c to your computer and use it in GitHub Desktop.
Trie contracts problem. Hackerrank
This file contains hidden or 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
class TrieNode{ | |
public static int ALPHABET_SIZE = 26; | |
TrieNode[] children = new TrieNode[ALPHABET_SIZE]; | |
int size = 0; | |
public int charIndex(char c){ | |
return c - 'a'; | |
} | |
public TrieNode getNode(char c){ | |
return children[charIndex(c)]; | |
} | |
public void setNode(char c,TrieNode node){ | |
children[charIndex(c)] = node; | |
} | |
public void add(String s){ | |
add(s,0); | |
} | |
public void add(String s,int index){ | |
size++; | |
if(index == s.length()) return; | |
char current = s.charAt(index); | |
TrieNode child = getNode(current); | |
if(child == null){ | |
child = new TrieNode(); | |
setNode(current,child); | |
} | |
child.add(s,index+1); | |
} | |
public int findCount(String s,int index){ | |
if(s.length() == index){ | |
return size; | |
} | |
TrieNode child = getNode(s.charAt(index)); | |
if(child == null) return 0; | |
return child.findCount(s, index+1); | |
} | |
} | |
public class Solution { | |
/* | |
* Complete the contacts function below. | |
*/ | |
static int[] contacts(String[][] queries) { | |
/* | |
* Write your code here. | |
*/ | |
int [] aux = new int[100001]; | |
int j = 0; | |
TrieNode root = new TrieNode(); | |
for(int i=0;i<queries.length;i++){ | |
if(queries[i][0].equals("add")){ | |
root.add(queries[i][1]); | |
} | |
else{ | |
int res = root.findCount(queries[i][1],0); | |
aux[j++] = res; | |
} | |
} | |
int [] res = new int[j]; | |
for(int i=0;i<j;i++){ | |
res[i] = aux[i]; | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment