面试题:
IBM全球有35万员工,名字由26个字母组成,长度不一。
1)请设计一个算法,能够快速查找出要查询的名字。
2)写出此算法的时间复杂度
3)如果对此算法进行测试,请写出测试用例
方法:字典树实现快速查找
字典树:是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
class Client_port {
public static void main(String[] args) {
Client_port cp = new Client_port();
cp.insert("liuxin");
System.out.println(cp.search_str("aaa"));
System.out.println(cp.search_str("liuxin"));
}
private final int SIZE = 26; // 每个节点能包含的子节点数,即需要SIZE个指针来指向其孩子
private Node root; // 字典树的根节点
private class Node {
private boolean isStr; // 标识该节点是否为某一字符串终端节点
private int num; // 标识经过该节点的字符串数。在计算前缀包含的时候会用到
private Node[] child; // 该节点的子节点
public Node() {
child = new Node[SIZE];
isStr = false;
num = 1;
}
}
public Client_port() {
root = new Node();
}
/**
* 检查字典树中是否完全包含字符串word
*/
public boolean search_str(String word) {
Node pNode = this.root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
// 在字典树中没有对应的节点,或者字符串倒数第二个对应不匹配则返回false
if (pNode.child[index] == null || (i + 1 == word.length() && pNode.child[index].isStr == false)) {
return false;
}
pNode = pNode.child[index];
}
return true;
}
/**
* 在字典树中插入一个词
*/
public void insert(String word) {
if (word == null || word.isEmpty()) {
return;
}
Node pNode = this.root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (pNode.child[index] == null) { // 如果不存在节点,则new一个一节点插入字典树
Node tmpNode = new Node();
pNode.child[index] = tmpNode;
} else {
pNode.child[index].num++; // 如果字典树中改路径上存在节点,则num加1,表示在该节点上有一个新的单词经过
}
pNode = pNode.child[index];
}
pNode.isStr = true;
}
public Node getRoot() {
return root;
}
}