1.前缀树
例子:
一个字符串类型的数组arr1,另一个字符串类型的数组arr2。arr2中有哪些字符,是arr1中出现的?请打印。arr2中有哪些字符,是作为arr1中某个字符串前缀出现的?请打印。arr2
中有哪些字符,是作为arr1中某个字符串前缀出现的?请打印 arr2中出现次数最大的前缀。
代码:
public static class TrieNode {
public int path;
public int end;
public TrieNode[] nexts;
public TrieNode() {
path = 0;
end = 0;
nexts = new TrieNode[26]; //26个字母,若有更多的字符,可以使用HashMap
}
}
public static class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
//插入操作
public void insert(String word) {
if (word == null) {
return;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
node.nexts[index] = new TrieNode();
}
node = node.nexts[index];
node.path++;
}
node.end++;
}
//删除操作
public void delete(String word) {
if (search(word) != 0) { //查询是否存在才可开始删除
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (--node.nexts[index].path == 0) {
node.nexts[index] = null;
return;
}
node = node.nexts[index];
}
node.end--;
}
}
//查询一条字符串插入了几次
public int search(String word) {
7.算法笔记——详解前缀数和贪心算法
最新推荐文章于 2024-08-13 14:56:59 发布
本文详细介绍了前缀树(Trie)的数据结构及其在字符串匹配问题中的应用,包括插入、删除和查找操作。同时,文章讨论了如何在面试中运用贪心算法解决问题的步骤,并给出了几个实例,如最小字典序字符串拼接、节省铜板的金条分割、最大化宣讲场次的会议室调度以及在有限资金和项目限制下获取最大收益的问题。这些实例展示了贪心策略的有效性和实用性。
摘要由CSDN通过智能技术生成