【问题标题】:How do I consider a space character in a trie?如何在 trie 中考虑空格字符?
【发布时间】:2022-01-25 13:52:59
【问题描述】:

比如我想在trie中插入“几个”,但是不知道怎么做:

public void insertWord(String wordName){
    for (int i = 0; i < wordName.length(); i++){
        if( current.children[wordName.charAt(i) - 'a'] == null)
            current.children[wordName.charAt(i) - 'a'] = new Node(wordName.charAt(i));
        current = current.children[wordName.charAt(i) - 'a'];
    }
}

我收到此错误:

线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:索引 -65 超出长度 29 的范围

数组长度等于29。

我该如何解决这个问题?

【问题讨论】:

  • 您可以决定忽略它。 trie 中的任何内容都不会对任何值进行特殊处理。

标签: java dictionary trie


【解决方案1】:

问题在于您使用表达式wordName.charAt(i) - 'a' 定义了children 数组的索引。但是空格的序数值比'a'的小很多,所以变成了负值。

相反,您可以在常量字符串的帮助下定义从字符到索引的转换:

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz ";

注意z 后面的空格。您可以添加更多字符,如果您想支持其他字符,如逗号、点、...大写字母、...等。 但是,这个字符串的长度不能大于children数组的长度。

然后,在您的函数中,您可以按如下方式使用该字符串:

    int key = ALPHABET.indexOf(wordName.charAt(i));
    if( current.children[key] == null)
        current.children[key] = new Node(wordName.charAt(i));
    current = current.children[key];

【讨论】:

    猜你喜欢
    • 2021-06-22
    • 2018-12-09
    • 2022-06-16
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多