You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSV内容存入Trie节点后search匹配失败问题求助

问题分析与解决

核心问题出在CSV解析逻辑,导致目标单词根本没被插入Trie:

  • 用csv.split(",")拆分"abacus,,,,,,,, trust,,"时,得到的数组是["abacus", "", "", "", "", "", "", "", "", "trust", "", ""],长度为12,完全不满足if (words.length == 2)的判断条件,所以abacus从未被插入Trie,自然搜不到。
  • 手动传入能匹配,说明Trie的insert和search方法本身是正常的,问题就卡在CSV读取这一步没执行插入操作。

修复方案

修改CSV解析部分,过滤拆分后产生的空字符串,只保留有效单词:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

// 你的其他代码...

try {
    while ((csv = br.readLine()) != null) {
        System.out.println(csv);
        // 拆分后先去除每个元素的首尾空格,再过滤空字符串
        String[] words = Arrays.stream(csv.split(","))
                               .map(String::trim)
                               .filter(s -> !s.isEmpty())
                               .toArray(String[]::new);
        // 有效单词数量为2时执行插入
        if (words.length == 2) {
            String word = words[0];
            int code = 0;
            trie.insert(word, code);
        }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    // 补上readLine可能抛出的IOException,否则会编译报错
    e.printStackTrace();
}
        
System.out.println(trie.search("abacus"));

额外提示

  • 要是确定有效单词之间用连续多个逗号分隔,也可以用split(",+")(匹配1个或多个逗号)来减少空字符串的生成,但后续仍需trim和过滤,避免首尾可能的空内容。

内容的提问来源于stack exchange,提问作者Tate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:55:30