【问题标题】:Fastest way to insert a word at the correct position in a dictionary在字典中正确位置插入单词的最快方法
【发布时间】:2010-12-12 03:47:24
【问题描述】:

目前,我只是将单词插入字典 (ArrayList<String>),然后像这样对字典进行排序:

dictionary.add(newWord);
Collections.sort(dictionary, new Comparator<String>(){
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }        
});

我正在尝试确定这种方式是否真的是最好的。当然,另一种方法是在字典中找到正确的点,然后将单词插入那里。问题是,我无法想出一种有效/可靠的方法来在字典中找到该点。我脑子里有一些想法在飞来飞去,但把笔写在纸上真的很棘手。

如果您知道如何操作,请不要发布任何大量代码答案。这是作业的一部分,所以你能不能告诉我你是怎么做的,而不是发布代码? (可能是伪代码?)

谢谢。

【问题讨论】:

  • 在编写比较器时要小心。如您所写,如果 s1 为空,您的代码将崩溃。你应该检查那个条件。

标签: java dictionary variable-assignment


【解决方案1】:

我会使用TreeSet&lt;String&gt; 而不是ArrayList&lt;String&gt;,因为TreeSet 使用字符串比较器来维护插入时的顺序。而TreeSet 不允许您添加空值,因为它使用的是字符串比较器。

import java.util.Set;
import java.util.TreeSet;

public class Dictionary
{
    public static void main(String[] args)
    {
        Set<String> dictionary = new TreeSet<String>();
        dictionary.add("zebra");
        dictionary.add("wildebeast");
        dictionary.add("aardvark");
        System.out.println(dictionary); // will be in the correct alphabetical order.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2017-09-27
    • 2018-04-14
    • 2012-05-28
    • 2015-04-16
    相关资源
    最近更新 更多