I have big set of urls and I want to implement an autocompletion. I don\'t like the complexity of the naive approach as it is linear with the set size:
for(S
The Regexp implementation java.util.regex.Pattern can efficiently handle prefixes:
StringBuilder buffer = new StringBuilder();
for (String prefix : prefixes) {
if (buffer.length() > 0)
buffer.append("|");
buffer.append(prefix);
}
Pattern prefixPattern = Pattern.compile("^(" + buffer + ")");
You can test all prefixes:
boolean containsPrefix = prefixPattern.matcher(stringToTest).find();
Note: for simplicity, prefix strings are not escaped. Regexp characters [, ], \, *, ?, $, ^, (, ), {, } and | have to be prefixed by \.