2012-01-22 18 views

回答

2

我會使用像TreeSet這樣的普通NavigableSet。它內置並支持範圍搜索。

NavigableSet<String> words = new TreeSet<String>(); 
// add words. 
String startsWith = ... 
SortedSet<String> matching = words.subSet(startsWith, startsWith + '\uFFFF'); 

如果你想要更多的內存效率,你可以使用一個數組。

List<String> words = new ArrayList<String>(); 
words.add("aa"); 
words.add("ab"); 
words.add("ac"); 
words.add("ba"); 
Collections.sort(words); 

String startsWith = "a"; 
int first = Collections.binarySearch(words, startsWith); 
int last = Collections.binarySearch(words, startsWith.concat("\uFFFF")); 
if (first < 0) first = ~first; 
if (last < 0) last = ~last - 1; 
for (int i = first; i <= last; i++) { 
    System.out.println(words.get(i)); 
} 
+0

此工具將是最好的 - http://sna-projects.com/cleo/quickstart.php –

相關問題