Finding entries in a TreeSet that contain a prefix

≯℡__Kan透↙ 提交于 2019-12-11 11:44:00

问题


I have a TreeSet in Java that contains Strings (specifically words). I need to write a method...

public boolean isValidPrefix(String prefix)

...which accepts a prefix as an argument and checks the TreeSet to see if any of its contained words begin with the prefix.

For example, given the prefix "CA" and a TreeSet containing {"DOG,"CAT","COW"}, my method would need to identify that there is a word "CAT" which starts with the prefix.

P.S. I would iterate through the TreeSet, but time complexity is an obvious constraint as the TreeList will be up to 200,000 words in many instances.


回答1:


If one String foo is a prefix of another String bar in the TreeSet, I believe it is a safe assumption for bar to immediately follow foo in the TreeSet.

Thus, I believe it suffices to take TreeSet.ceiling(foo) and check whether foo is a prefix of it.

From the documentation of that function, we see that it returns exactly the element that would follow the given element in order.

Returns the least element in this set greater than or equal to the given element, or null if there is no such element.

The algorithm would thus be :

  1. Call TreeSet.ceiling() on the input. If the return value is null, then return false.
  2. If the return value is not null, return whether the input is a valid prefix of the return value.


来源:https://stackoverflow.com/questions/24664715/finding-entries-in-a-treeset-that-contain-a-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!