public class TrieST<Value> {
private static final int R = 256;
private Node root;
private int n;
private static class Node {
private Object val;
private Node[] next = new Node[R];
}
public TrieST() {}
public Value get(String key) {
if (key == null)
throw new IllegalArgumntException("argument to get() is null");
Node x = get(root, key, 0);
if (x == null) return null;
return (Value) x.val;
}
private Node get(Node x, String key, int d) {
if (x == null) return null;
if (d == key.length()) return x;
char c = key.charAt(d);
return get(x.next[c], key, d+1);
}
public boolean contains(String key) {
if (key == null)
throw new IllegalArgumentException("argument to contains() is null");
return get(root, key, 0) != null;
}
public void put(String key, Value val) {
if (x == null) x = new Node();
if (d == key.length()) {
if (x.val == null) n++;
x.val = val;
return x;
}
char c = key.charAt(d);
x.next[c] = put(x.next[c], key, d+1);
return x;
}
public List<String> keyWithPrefix(String prefix) {
List<String> res = new ArrayList<>();
Node x = get(root, prefix, 0);
collect(x, new StringBuilder(prefix), res);
return res;
}
private void collect(Node x, StringBuilder prefix, List<String> res) {
if (x == null) return;
if (x.val != null) res.add(prefix.toString());
for (char c = 0; c < R; c++) {
prefix.append(c);
collect(x.next[c], prefix, res);
prefix.deleteCharAt(prefix.length()-1);
}
}
}
//2
class Trie {
public Node root;
class Node {
public boolean idEnd;
public Node[] children = new Node[26];
public Node(){}
}
/** Initialize your data structure here. */
public Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node ws = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (ws.children[c - 'a'] == null) {
ws.children[c - 'a'] = new Node();
}
ws = ws.children[c - 'a'];
}
ws.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Node x = getNode(word);
if(x == null) return false;
return ws.isEnd;
}
private Node get(String key) {
Node ws = root;
for (int i = 0; i < key.length(); i++) {
char c = word.charAt(i);
if (ws.children[c - 'a'] == null) {
return null;
}
ws = ws.children[c - 'a'];
}
return ws;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public List<String> startsWith(String prefix) {
List<String> res = new ArrayList<>();
Node x = get(prefix);
if (x == null) return res;
collect(x, new StringBuilder(prefix), res);
return res;
}
private void collect(Node x, StringBuilder prefix, List<String> res) {
if (x == null) return;
if (x.isEnd) res.add(prefix.toString());
for (int i = 0; i < R; i++) {
prefix.append(i + 'a');
collect(x.children[c], prefix, res);
prefix.deleteCharAt(prex.length()-1);
}
}
}
04-01
263
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)