-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathShortestUniquePrefix.java
More file actions
90 lines (67 loc) · 2.17 KB
/
Copy pathShortestUniquePrefix.java
File metadata and controls
90 lines (67 loc) · 2.17 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Question link: https://practice.geeksforgeeks.org/problems/shortest-unique-prefix-for-every-word/1
*/
import java.util.*;
public class ShortestUniquePrefix {
public static void main(String[] args) {
String[] words = {"zebra", "dog", "duck", "dove"};
Solution solution = new Solution();
String[] prefixes = solution.findPrefixes(words, 4);
for(String s: prefixes)
System.out.println(s);
}
static class Solution {
static class TrieNode {
char val;
int count;
Map<Character, TrieNode> next;
TrieNode() {
count = 0;
next = new HashMap<Character, TrieNode>();
}
TrieNode(char c) {
count = 1;
val = c;
next = new HashMap<Character, TrieNode>();
}
void insert(char c) {
next.put(c, new TrieNode(c));
}
void incCount() {
count++;
}
}
static String[] findPrefixes(String[] arr, int N) {
// code here
TrieNode root = new TrieNode();
for(String s: arr) {
createTrie(root, s, 0);
}
String[] prefixes = new String[N];
int i = 0;
for(String s: arr) {
prefixes[i++] = getPrefix(root, s, 0, new StringBuilder(""));
}
return prefixes;
}
private static void createTrie(TrieNode root, String s, int x) {
if(x == s.length())
return;
char c = s.charAt(x);
if(!root.next.containsKey(c)) {
root.insert(c);
}
else {
root.next.get(c).incCount();
}
createTrie(root.next.get(c), s, x+1);
}
private static String getPrefix(TrieNode root, String s, int x, StringBuilder st) {
if(root.count == 1)
return st.toString();
char c = s.charAt(x);
st.append(c);
return getPrefix(root.next.get(c), s, x + 1, st);
}
}
}