How to create a simple prefix index in Java?

后端 未结 4 388
Happy的楠姐
Happy的楠姐 2020-12-19 13:01

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         


        
4条回答
  •  渐次进展
    2020-12-19 13:34

    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 \.

提交回复
热议问题