我正在尝试根据文本文件搜索一组常见英语单词,以查看其中是否包含特定单词。由于这个数组有超过 700,000 个单词,并且需要检查大约 1000 个单词是否在数组中多次,我认为根据长度将单词分成单独的数组或列表会更有效。有没有一种简单的方法可以在不使用 switch 或大量 if 语句的情况下做到这一点?就像这样:
for(int i = 0; i < commonWordArray.length; i++) {
if(commonWordArray[i].length == 2) {
twoLetterList.add(commonWordArray[i]);
else if(commonWordArray[i].length == 3) {
threeLetterList.add(commonWordArray[i]);
else if(commonWordArray[i].length == 4) {
fourLetterList.add(commonWordArray[i]);
}
...etc
}
然后在检查单词时做同样的事情:
for(int i = 0; i < checkWords.length; i++) {
if(checkWords[i].length == 2) {
if(twoLetterList.contains(checkWords[i])) {
...etc
}
最佳答案
第 1 步
创建词桶。
ArrayList<ArrayList<String>> buckets = new ArrayList<>();
for(int i = 0; i < maxWordLength; i++) {
buckets.add(new ArrayList<String>());
}
第 2 步
将单词添加到您的存储桶中。
buckets.get(word.length()).add(word);
这种方法的缺点是您的某些存储桶可能未被使用。如果您只过滤常见英语单词,这不是问题,因为它们的长度不超过 30 个字符。创建 10-15 个额外列表对于计算机来说是微不足道的开销。最大的不常见但非技术性单词有 183 个字符。技术单词超过 180,000 个字符,此时这种方法显然不切实际。
这种方法的优点是 ArrayList.get()
和 ArrayList.add()
都以恒定 (O(1)) 的时间运行。
关于java - 根据Java中的单词长度将常见英语单词数组拆分为单独的列表/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22230033/