java中trie_在Java中实现Trie

我用Java实现了Trie数据结构,但是在运行代码时没有得到正确的答案 . 我用一些简单的字符串构建了trie . 我正在搜索单词和前缀,但结果不合适 . 我已经尝试了很多调试但仍然找不到它可能出错的地方 .

Trie.java:

public class Trie {

public class Vertex {

public int words;

public int prefixes;

public Vertex edges[] = new Vertex[26];

public Vertex() {

this.words = 0;

this.prefixes = 0;

}

}

private Vertex root;

Trie() {

this.root = new Vertex();

}

private void addWord(Vertex vertex, String word) {

if (word.isEmpty()) {

vertex.words++;

} else {

vertex.prefixes++;

int indexOfNextChar = (int) word.charAt(0) - 97;

vertex.edges[indexOfNextChar] = new Vertex();

this.addWord(vertex.edges[indexOfNextChar], word.substring(1));

}

}

private int countWords(Vertex vertex, String word) {

if (!word.isEmpty()) {

int indexOfNextChar = (int) word.charAt(0) - 97;

if (vertex.edges[indexOfNextChar] == null) {

return 0;

} else {

return this.countWords(vertex.edges[indexOfNextChar], word.substring(1));

}

} else {

return vertex.words;

}

}

private int countPrefixes(Vertex vertex, String word) {

if (!word.isEmpty()) {

int indexOfNextChar = (int) word.charAt(0) - 97;

if (vertex.edges[indexOfNextChar] == null) {

return 0;

} else {

return this.countPrefixes(vertex.edges[indexOfNextChar], word.substring(1));

}

} else {

return vertex.prefixes;

}

}

public void addWord(String word) {

this.addWord(this.root, word.toLowerCase());

}

public int countPrefixes(String word) {

if (word.length() != 0) {

return this.countPrefixes(this.root, word.toLowerCase());

}

return -1;

}

public int countWords(String word) {

if (word.length() != 0) {

return this.countWords(this.root, word.toLowerCase());

}

return -1;

}

}

TrieTester.java

public class TrieTester {

public static void main(String[] args) {

Trie trie = new Trie();

trie.addWord("Ayush");

trie.addWord("Ayur");

trie.addWord("Ayub");

trie.addWord("Ayan");

trie.addWord("Bhushan");

// Should output 0, outputs 0

System.out.println("Count of word Ayus: " + trie.countWords("Ayus"));

// Should output 1, outputs 0

System.out.println("Count of word Ayush: " + trie.countWords("Ayush"));

// Should output 4, outputs 1

System.err.println("Count of prefix Ay: " + trie.countPrefixes("Ay"));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值