-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathShortestUniquePrefixForEveryWord.java
63 lines (60 loc) · 1.61 KB
/
ShortestUniquePrefixForEveryWord.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*https://practice.geeksforgeeks.org/problems/shortest-unique-prefix-for-every-word/0/*/
//store frequencies of each node and find the first node with frequency 1
class TrieNode
{
HashMap<Character,TrieNode> map;
int freq;
boolean isEndOfWord;
TrieNode()
{
map = new HashMap<Character,TrieNode>();
freq = 0;
isEndOfWord = false;
}
}
class Trie
{
HashMap<String,StringBuilder> map;
TrieNode root;
Trie()
{
root = new TrieNode();
map = new HashMap<String,StringBuilder>();
}
public void insert(String word)
{
TrieNode temp = root;
for (int i = 0; i < word.length(); ++i)
{
if (!temp.map.containsKey(word.charAt(i)))
{
temp.map.put(word.charAt(i), new TrieNode());
}
temp = (TrieNode)temp.map.get(word.charAt(i));
++temp.freq;
}
temp.isEndOfWord = true;
}
public String getPrefix(String word)
{
TrieNode temp = root;
StringBuilder result = new StringBuilder("");
int i = 0;
while (temp.freq != 1)
{
result.append(word.charAt(i));
temp = (TrieNode)temp.map.get(word.charAt(i++));
}
return new String(result);
}
}
class Solution {
static String[] findPrefixes(String[] arr, int N) {
Trie trie = new Trie();
String[] result = new String[arr.length];
for (String word : arr) trie.insert(word);
for (int i = 0; i < arr.length; ++i)
result[i] = trie.getPrefix(arr[i]);
return result;
}
}