How to create a simple prefix index in Java?

I have a large set of URLs and I want to implement autocomplete. I do not like the complexity of the naive approach, since it is linear with a given size:

for(String url: urls) if(url.startsWith(input) {doSomething();}

Now I know that in the Hash Set the function "contains ()" works in "O (1)", but not "containsPrefix ()". Is there an easy way without using a large library like Lucene or coding it? I would not have a problem with this, but it seems redundant for such a simple problem, so I want to know if there is an existing simple solution :-)

From my computer science classes, I remember a tree consisting of fragments of a string, but I forget how it was called. It worked as follows:

[car, care, carrot,carrotville]->

car
|
-/
-e
-rrot
  |
  ----ville

P.S.: , , ? , a b, b a?

+5
4

, Trie, , :

- , , . , no node , node; , . node , node,

.

+2

Regexp java.util.regex.Pattern :

StringBuilder buffer = new StringBuilder();
for (String prefix : prefixes) {
    if (buffer.length() > 0)
        buffer.append("|");
    buffer.append(prefix);
}
Pattern prefixPattern = Pattern.compile("^(" + buffer + ")");

:

boolean containsPrefix = prefixPattern.matcher(stringToTest).find();

Note. For simplicity, prefix strings are not escaped. Regular characters [,], \, *,?, $, ^, (,), {,} AND | must have the prefix \.

0
source

All Articles