It’s a pretty common algorithm in command line parsing. Given a set of predefined long option names — compute the shortest prefix that uniquely identifies one of these options. So for instance, for the following options:
-help
-hostname
-portnumber
-name
-polymorphic
This would be the output:
-he
-ho
-por
-n
-pol
I’m thinking two possible ways of doing this — either as a tree:
*
/ | \
/ | \
H N P
/ \ |
E O O
/ \
R L
Or by searching for substrings:
for (String s : strings) {
for (int i = 1; i < s.length(); s++) {
if (search(strings,s.substring(0,i)) == 1) {
result.add(s.substring(0,i);
break;
}
}
}
So, question is:
- Which would you go for?
- Am I missing an obvious third way?
The “tree” solution is a special case (well, actually it’s pretty general) of a Patricia trie.
The first will generally be faster to lookup. The memory considerations probably aren’t relevant to your context, since it’s not permanently used and you’re only performing the “lookup” once.