All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.conqat.lib.commons.tree.Trie Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) CQSE GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.conqat.lib.commons.tree;

import java.util.HashMap;
import java.util.Map;

import org.conqat.lib.commons.string.StringUtils;

/**
 * Simple, efficient implementation of a trie that maps prefixes to objects of the generic type.
 */
public class Trie {

	private class TrieNode {

		private T value;

		private Map next = new HashMap<>();
	}

	private TrieNode root = new TrieNode();

	/**
	 * Map the prefix to the given value.
	 */
	public void put(String prefix, T value) {
		TrieNode currentNode = root;
		for (Character ch : StringUtils.splitChars(prefix)) {
			TrieNode nextNode = currentNode.next.get(ch);
			if (nextNode == null) {
				nextNode = new TrieNode();
				currentNode.next.put(ch, nextNode);
			}
			currentNode = nextNode;
		}
		currentNode.value = value;
	}

	/**
	 * Returns the value associated with the longest known prefix of this sequence, or null if no known
	 * prefix exists.
	 */
	public T getLongestPrefix(String sequence) {
		T currentBestMatch = null;
		TrieNode currentNode = root;
		for (Character ch : StringUtils.splitChars(sequence)) {
			currentNode = currentNode.next.get(ch);
			if (currentNode == null) {
				// Reached a leaf node in the Trie
				return currentBestMatch;
			} else if (currentNode.value != null) {
				currentBestMatch = currentNode.value;
			}
		}
		return currentBestMatch;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy