Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another. Input: arr[] = {"zebra", "dog", "duck", "dove"} Output: dog, dov, du, z Explanation: dog => dog dove = dov duck = du z => zebra Input: arr[] = {"geeksgeeks", "geeksquiz", "geeksforgeeks"}; Output: geeksf, geeksg, geeksq}
思路:用trie来build字典,build的时候count一下每个字符出现的次数,然后对每个string进行查询,第一count为1的node,即可返回shortest prefix了。
public class shortestPrefix {
private TrieNode root;
public shortestPrefix() {
root = new TrieNode();
}
public static void main(String[] args) {
String strs[] = {"zebra", "dog", "duck", "dove"};
shortestPrefix p = new shortestPrefix();
p.findShortestPrefix(strs);
}
public void insert(String word) {
if(word == null || word.length() == 0) return;
TrieNode curNode = root;
for(int i=0; i<word.length(); i++) {
char c = word.charAt(i);
int index = c-'a';
if(curNode.array[index] == null){
TrieNode temp = new TrieNode();
curNode.array[index] = temp;
curNode = temp;
curNode.count = 1;
} else {
curNode.array[index].count++;
curNode = curNode.array[index];
}
}
curNode.isword = true;
}
public void findShortestPrefix(String[] strs) {
// build trie;
for(int i=0; i<strs.length; i++) {
String str = strs[i];
insert(str);
}
// find shortest prefix;
for(int i=0; i<strs.length;i++){
String str = strs[i];
TrieNode curNode = root;
StringBuilder sb = new StringBuilder();
for(int j=0; j<str.length(); j++){
char c = str.charAt(j);
int index = c-'a';
if(curNode.array[index].count == 1){
sb.append(c);
System.out.println(sb.toString());
break;
} else {
sb.append(c);
curNode = curNode.array[index];
}
}
}
}
public class TrieNode {
public TrieNode[] array;
public int count = 0;
public boolean isword;
public TrieNode() {
array = new TrieNode[26];
}
}
}