HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Find a prefix of a query string in the values of a Map

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mapthevaluesqueryfindprefixstring

Problem

I have a hash map which maps to some strings which serve as prefixes and are of small length (max length is 6):

Map map = new HashMap<>();  
map.put("codeA", "100");  
map.put("codeB", "7");  
map.put("codeC", "0012");  
etc


This is fine so far, but I also need when provided an input string to actually break it into 2 parts if the string has a prefix that matches one of the values in my map.

What I do is:

boolean found = false;  

String [] result;  
for(Entry e: map.entrySet()) {  
   String code = e.getKey();  
   String value = e.getValue();  
   if(value.length >= inputString.length) continue;    
   if(inputString.startsWith(value)) {  
       result = new String[2];  
       result[0] = value;  
       result[1] = inputString.substring(value.length + 1);  
       found = true;  
       break;  
     }  
}    
return result;


Could this be improved? Could I have been using some additional datastructure/API for this?

I am interested in an approach in Java 7 without any extra libs. The HashMap has ~400 entries and the input string 8-11 characters.

I would need a way to get the prefix having the code (hence the HashMap) and break the input string into the prefix and the rest part.

Solution

Trie

A trie would solve this problem perfectly. With a trie, you could search all your prefixes in \$O(n)\$ time, where \$n\$ is the length of the input string. You current implementation requires \$O(m*n)\$ time, where \$m\$ in the number of prefixes and \$n\$ is the length of the input string.

Of course, the trie solution will be much more complex than your existing solution, so you will need to weigh the performance benefits of using a trie versus the simplicity of using a HashMap.

Context

StackExchange Code Review Q#106761, answer score: 5

Revisions (0)

No revisions yet.