【发布时间】:2016-07-28 08:02:21
【问题描述】:
我正在编写自己的基数排序方法来对字符串中的单词进行排序(the big black cat sat on the
beautiful brown mat 将被排序为beautiful big black brown cat mat on sat the the)。该方法接收单个单词的 List(我自己的 List 接口)并重新排序列表。
到目前为止,这是我的方法:
public static void stringRadixSort(List<String> list, int letters) {
List<String>[] buckets = (List<String>[]) Array.newInstance(List.class, 26);
int letterNumber = 1; //Sorts list by 1st letter of each word, then 2nd etc.
for (int i = 0; i < letters; i++) {
while (!list.isEmpty()) {
String word = list.remove(list.first());
if (word.length() > letters) throw new UnsortableException("The list contains a word that holds more letters than the given maximum number of letters."
+ "\nMax Letters: " + letters + "\nWord: " + word);
String letter = word.substring(letterNumber - 1, letterNumber); //EXCEPTION THROWN
char ch = letter.charAt(0);
int index = ch - 'a'; //gets index of each letter ('a' = buckets[0], 'z' = buckets[25]
if (buckets[index] == null) {
buckets[index] = new LinkedList<String>();
}
buckets[index].insertLast(word);
}
for (int j = 0; j < buckets.length; j++) {
if (buckets[j] != null) {
while (!buckets[j].isEmpty()) {
list.insertLast(buckets[j].remove(buckets[j].first()));
}
}
}
letterNumber++;
}
}
我的方法的(唯一,我希望)问题是,当我阅读单词的每个字符时,我会创建单词的单个字母子字符串。由于外部for 循环运行letters 次(其中letters 是列表中单词的最大长度),当此循环的迭代大于当前单词的长度时,将引发异常 -即letterNumber > word.length() - 因此它尝试使用大于字符串长度的字符串索引创建子字符串。
如何调整我的方法,使其仅创建每个单词的子字符串,直到 letterNumber == word.length(),然后还能够将排序算法应用于这些较短的单词 - “a”将变为“aa”之前。
【问题讨论】:
-
列表中似乎有一个空字。如果在非单词字符上拆分并且它们位于开头或结尾,或者没有考虑到单词之间可能有多个非单词字符,则可能会发生这种情况。
标签: java string sorting substring radix-sort