我从 Code Review 中找到了这个 trie 实现,它运行良好,我已经以某种方式对其进行了更改以适应我的程序的需求,现在我想操纵这个find()
函数,以便我可以将结果放在一个数组中。谢谢。这是课程代码:
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class AutoComplete {
private final Map<Character, HashMap> root = new HashMap<Character, HashMap>();
private final Character END_CHARACTER = '$';
/**
* Will create an empty AutoComplete
*/
public AutoComplete() {}
/**
* Will create an AutoComplete filled from a Collection of String items
*
* @param items A Collection (Vector, List etc.) of String items
*/
public AutoComplete (Collection<String> items)
{
for (String s : items)
{
internalAdd(s);
}
}
/**
* Will create an AutoComplete filled from an array of String items
*
* @param items An array of String items
*/
public AutoComplete (String[] items)
{
for (String s : items){
internalAdd(s);
}
}
/**
* Will add a String to the AutoComplete
*
* @param item The String item to add
* @return Returns true if item is added, false if item already exists
*/
public boolean add(String item)
{
if (find(item) != null)
{
internalAdd(item);
return true;
}
else
{
return false;
}
}
/**
* Will return an array of Strings that start with the given prefix
*
* @param prefix The prefix to search for
* @return An array of Strings starting with the prefix. Will return null if nothing is found.
*/
public String[] find(String prefix)
{
Map<Character, HashMap> node = root;
for (int i = 0; i < prefix.length(); i++)
{
if (node.isEmpty())
{
return null;
}
Character character = prefix.charAt(i);
if (node.containsKey(character))
{
node = node.get(character);
}
else
{
return null;
}
}
// return found items as an array
}
private boolean internalAdd(final String s)
{
Map<Character, HashMap> node = root;
for (int i = 0; i < s.length(); i++)
{
Character character = s.charAt(i);
if(node.isEmpty() || !node.containsKey(character))
{
internalAdd(s.substring(i), node);
break;
}
node = node.get(character);
}
node.put(END_CHARACTER, new HashMap());
return true;
}
private void internalAdd(final String s, Map<Character, HashMap> node)
{
for (int i = 0; i < s.length(); i++)
{
Character character = s.charAt(i);
node.put(character, new HashMap());
node = node.get(character);
}
}
}