forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestUniquePrefix.java
More file actions
85 lines (63 loc) · 1.82 KB
/
ShortestUniquePrefix.java
File metadata and controls
85 lines (63 loc) · 1.82 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
package Trees;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Author - archit.s
* Date - 09/11/18
* Time - 4:57 PM
*/
public class ShortestUniquePrefix {
class TrieNode{
boolean isUnique;
Map<Character, TrieNode> map;
public TrieNode(){
map = new HashMap<>();
isUnique = true;
}
public void insert(TrieNode head, String s){
if(head == null){
return;
}
TrieNode cur = head;
for(int i=0;i<s.length();i++){
Character c = s.charAt(i);
if(!cur.map.containsKey(c)){
cur.map.put(c, new TrieNode());
}
else{
cur.map.get(c).isUnique = false;
}
cur = cur.map.get(c);
}
}
public String getUnique(TrieNode head, String s){
StringBuilder temp = new StringBuilder();
if(head == null){
return temp.toString();
}
TrieNode cur = head;
for(int i=0;i<s.length();i++){
Character c = s.charAt(i);
temp.append(c);
if(cur.map.containsKey(c) && cur.map.get(c).isUnique){
return temp.toString();
}
cur = cur.map.get(c);
}
return temp.toString();
}
}
public ArrayList<String> prefix(ArrayList<String> A) {
TrieNode head = new TrieNode();
TrieNode t = new TrieNode();
for(String temp: A){
t.insert(head, temp);
}
ArrayList<String> r = new ArrayList<>();
for(String temp : A){
r.add(t.getUnique(head, temp));
}
return r;
}
}