2つのセットの場合:
word
があなたの言葉(例: "banana"
)の場合:
int cmp = word.compareTo("melon");
if (cmp < 0) {
//it belongs to the first set
} else if (cmp > 0) {
//it belongs to the second set
} else {
//the word is "melon"
}
n
セットの場合:
Place the dividing words into an ArrayList
(call it dividers
) in alphabetical order:
ArrayList dividers = new ArrayList();
//... populate `dividers` ...
Collections.sort(dividers);
これで、 Collections.binarySearch()
を使って、単語がどのセットに属するかを調べることができます:
int pos = Collections.binarySearch(dividers, word);
if (pos >= 0) {
//the word is the divider between sets `pos` and `pos+1`
} else {
int num = -(pos + 1);
//the word belong to set number `num`
}
(ここでは、セットは0から番号が付けられています)。