V
- the type of values managed by the triepublic class Trie<V> extends Object
A trie is a highly efficient data structure for iterating through a string and retrieving a previously stored value. Checking containment or retrieving a value has guaranteed O(n) runtime, where n is the length of the processed string, independent of the size of the trie.
An Example: If we have a list of stop words: "one", "two", "three" and want to detect if these occur in a given text, we can do the following:
Trie<Boolean> trie = Trie.create();
trie.put("one", true);
trie.put("two", true);
trie.put("three", true);
String check = "I'd like to have three beer please";
Trie.ContainmentIterator<Boolean> iter = trie.iterator();
for(int i = 0; i < check.length(); i++) {
if (!iter.doContinue(check.charAt(i))) {
if (iter.isCompleted()) {
System.out.println("Found!");
} else {
iter.resetWith(check.charAt(i));
}
}
}
Modifier and Type | Class and Description |
---|---|
static interface |
Trie.ContainmentIterator<V>
Represents an iterator which navigates through the trie character by character.
|
Constructor and Description |
---|
Trie() |
Modifier and Type | Method and Description |
---|---|
boolean |
containsKey(CharSequence key)
Determines if the given key is contained in the trie.
|
static <V> Trie<V> |
create()
Creates a new
Trie without forcing you to re-type the generics. |
V |
get(CharSequence key)
Returns the value associated with the given key.
|
Set<String> |
getAllKeysBeginningWith(String prefix)
|
Trie.ContainmentIterator<V> |
iterator()
Generates a new iterator for the underlying trie.
|
Set<String> |
keySet()
Retrieves all keys that are stored in this
Trie . |
void |
put(CharSequence key,
V value)
Associates the given key with the given value.
|
int |
size()
Retrieves the number of keys that are stored in this
Trie . |
public static <V> Trie<V> create()
Trie
without forcing you to re-type the generics.V
- the type of values managed by the trieTrie
public boolean containsKey(@Nonnull CharSequence key)
key
- the key to check for.public Trie.ContainmentIterator<V> iterator()
public V get(@Nonnull CharSequence key)
key
- the path to navigate throughpublic void put(@Nonnull CharSequence key, @Nonnull V value)
key
- the path to store the given valuevalue
- the value to store in the trie.public int size()
Trie
.Copyright © 2018. All rights reserved.