208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

class TrieNode {
public char val;
public boolean isWord;
public TrieNode[] children;
public TrieNode(char c) {
this.val = c;
this.isWord = false;
this.children = new TrieNode[26];
}
}

public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}

public void insert(String word) {
TrieNode tn = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (tn.children[c - 'a'] == null)
tn.children[c - 'a'] = new TrieNode(c);
tn = tn.children[c - 'a'];
}
tn.isWord = true;
}

public boolean search(String word) {
TrieNode tn = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (tn.children[c - 'a'] == null)
return false;
tn = tn.children[c - 'a'];
}
return tn.isWord;
}

public boolean startsWith(String prefix) {
TrieNode tn = root;
for(int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (tn.children[c - 'a'] == null)
return false;
tn = tn.children[c - 'a'];
}
return true;
}
}
posted @ 2022-11-24 10:58  MarkLeeBYR  阅读(20)  评论(0)    收藏  举报