Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class Autocomplete {
  4. private final Term[] terms;
  5.  
  6. // Initializes the data structure from the given array of terms.
  7. // O(N log N)
  8. public Autocomplete(Term[] terms) {
  9. if (terms == null)
  10. throw new java.lang.NullPointerException("terms cannot be null.");
  11.  
  12. for (int i = 0; i < terms.length; i++)
  13. if (terms[i] == null)
  14. throw new java.lang.NullPointerException("Any item in terms cannot be null.");
  15.  
  16. Arrays.sort(terms, Term.byLexicographicOrder());
  17. this.terms = terms;
  18. }
  19.  
  20. // Returns all terms that start with the given prefix, in descending order of weight.
  21. // O(log N + M log M)
  22. public Term[] allMatches(String prefix) {
  23. if (prefix == null)
  24. throw new java.lang.NullPointerException("prefix cannot be null.");
  25.  
  26. int matchesCount = numberOfMatches(prefix);
  27. if (matchesCount == 0) return new Term[0];
  28. Term[] matches = new Term[matchesCount];
  29. Term key = new Term(prefix, 0);
  30. int first = RangeBinarySearch.firstIndexOf(this.terms, key, Term.byPrefixOrder(prefix.length()));
  31. for (int i = 0; i < matchesCount; i++)
  32. matches[i] = this.terms[i + first];
  33.  
  34. Arrays.sort(matches, Term.byReverseWeightOrder());
  35. return matches;
  36. }
  37.  
  38.  
  39. // Returns the number of terms that start with the given prefix.
  40. // O(log N)
  41. public int numberOfMatches(String prefix) {
  42. if (prefix == null)
  43. throw new java.lang.NullPointerException("prefix cannot be null.");
  44.  
  45. Term key = new Term(prefix, 0L);
  46. int first = RangeBinarySearch.firstIndexOf(this.terms, key, Term.byPrefixOrder(prefix.length()));
  47. int last = RangeBinarySearch.lastIndexOf(this.terms, key, Term.byPrefixOrder(prefix.length()));
  48. if (first == -1 && last == -1) return 0;
  49. return last - first + 1;
  50. }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement