Implement T9 Dictionary using Trie?

[亡魂溺海] 提交于 2019-12-06 15:42:19

1 - You File doesn't contains characters. It is binary so you should use FileInputStream object to read it.

2 - In reading file and adding string in your Trie you should verify that this string is not null, otherwise it can throws a NullPointerException. You can run your file like this:

When I run this I find that the exception occurs on this line:

root = new Node(this.getVal(s.charAt(0)));

Let's unroll this, you're passing the first character of the "word" (ie the String, s) to the getVal(), and this in turn will return an int if, and only if, that character is a lowercase letter, a-z.

When I run the file the "word" is 6724 yahoo - this is the first line of the dictionary text file you linked to. There is nothing in your code to clean up this line to get to the actual word itself, instead you are facing a series of spaces and then a number.

So the reason it fails is because you're effectively going this.getVal(" "). If you call map.get() and the key doesn't exist it'll return null (as described in the Map documentation).

One simple way of getting to the word itself and not the whitespace or frequency number is to first process the string:

s = s.trim(); // removes all leading and trailing whitespace
String word = s.substring(s.indexOf(" ")+1); // extract just the word after the space

And then you can pass the first character of word:

root = new Node(this.getVal(word.charAt(0)));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!