CareerCup Trie Prefix Tree

2024-03-17 15:58
文章标签 tree trie prefix careercup

本文主要是介绍CareerCup Trie Prefix Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Return a shortest prefix of <code>word</code> that is <em>not</em> a prefix of any word in the <code>list</code> 

e.g. 
word: cat, it has 4 prefixes: “”, “c”, “ca”, “cat” 
list: alpha, beta, cotton, delta, camera 

 

Result is “cat”

 

-----------------------------------------------------------------------------

Use unordered_map to replace array 

 

#include <stdio.h>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <iostream>
using namespace std;class Trie
{public:int num;//to remember how many word can reach here,that is to say,prefixbool terminal;//If terminal==true ,the current point has no following pointunordered_map<char, Trie*> son;Trie(bool terminal = false, int num = 1):terminal(terminal), num(num){}
};
typedef unordered_map<char, Trie*>::iterator IT;
Trie* BuildTrie()// create a new node
{Trie *root=new Trie(false, 0);return root;
}
void Insert(Trie* root, string& s)// insert a new word to Trie tree
{++root->num;for(int i=0; i<s.length(); ++i){if (root->son.find(s[i]) == root->son.end()) {Trie* tmp = new Trie(false, 1);root->son.insert(make_pair(s[i],tmp));}elseroot->son[s[i]]->num++;root = root->son[s[i]];}root->terminal=true;
}
void Delete(Trie *root)// delete the whole tree
{if(root!=NULL)  {for (IT it = root->son.begin(); it != root->son.end(); ++it) Delete(it->second);delete root; root=NULL;}
}
Trie* Find(Trie *root,string& s)//trie to find the current word
{for(int i=0;i<s.length();++i)if(root->son[s[i]]!=NULL)root=root->son[s[i]];else return NULL;return root;
}
void ListAll(Trie *root,string& cur)
{if (root->terminal)cout << cur << endl;for (IT it = root->son.begin(); it != root->son.end(); ++it) {string next = cur + it->first;ListAll(it->second, next);}
}void dfs(Trie* root, int K, string& cur, vector<string>& longeststr) {if (root->num < K)return;int ls = longeststr.size(), l0 = ls == 0 ? 0 : longeststr[0].length(), cl = cur.length();if (root->num == K) {if (ls == 0)longeststr.push_back(cur);else if (l0 < cl){longeststr.clear();longeststr.push_back(cur);}else if(l0 == cl)longeststr.push_back(cur);}for (IT it = root->son.begin(); it != root->son.end(); ++it) {string next = cur + it->first;if (it->second->num >= K)dfs(it->second, K, next, longeststr);}  
}
vector<string> isExist(Trie *root, int K) {string cur = "";vector<string> longeststr;dfs(root, K, cur, longeststr);return longeststr;
}int main() {Trie* trie = BuildTrie();string str[] = {"abc", "ab", "ade", "dcef"};for (int i = 0; i < 4; ++i)Insert(trie, str[i]);string s = "ab";Trie *searchWord = Find(trie, s);ListAll(trie, s);		vector<string> res = isExist(trie, 1);return 0;
}

 

 

 

 

 

 

------------------------------------------------------------------------------

Use array

 

#include <stdio.h>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
const int sonnum=26,base='a';
class Trie
{public:int num;//to remember how many word can reach here,that is to say,prefixbool terminal;//If terminal==true ,the current point has no following pointTrie *son[sonnum];//the following pointTrie(bool terminal = true, int num = 0):terminal(terminal), num(num){for (int i = 0; i < sonnum; ++i)son[i] = NULL;}
};
Trie* BuildTrie()// create a new node
{Trie *root=new Trie(true, 0);root->terminal = false;return root;
}
void Insert(Trie* root, string& s)// insert a new word to Trie tree
{for(int i=0; i<s.length(); ++i){if(root->son[s[i]-base] == NULL)root->son[s[i]-base]=new Trie();else root->son[s[i]-base]->num++;root->terminal = false;root=root->son[s[i]-base];}root->terminal=true;
}
void Delete(Trie *root)// delete the whole tree
{if(root!=NULL){for(int i=0;i<sonnum;++i)if(root->son[i]!=NULL)Delete(root->son[i]);delete root; root=NULL;}
}
Trie* Find(Trie *root,string& s)//trie to find the current word
{for(int i=0;i<s.length();++i)if(root->son[s[i]-base]!=NULL)root=root->son[s[i]-base];else return NULL;return root;
}
void ListAll(Trie *root,string& cur)
{if (root->terminal) {cout << cur;return;}else {for (int i = 0; i < sonnum; ++i)if (root->son[i]) {        string tmp = "a";tmp[0] += i;string next = cur + tmp;ListAll(root->son[i], next);		  }}
}int main() {Trie* trie = BuildTrie();string str[] = {"abc", "ab", "ade", "ace"};for (int i = 0; i < 4; ++i)Insert(trie, str[i]);string s = "a";Trie *searchWord = Find(trie, s);ListAll(searchWord, s);		return 0;
}

The above code is not right:

 

#include <stdio.h>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
const int sonnum=26,base='a';
class Trie
{public:int num;//to remember how many word can reach here,that is to say,prefixbool terminal;//If terminal==true ,the current point has no following pointTrie *son[sonnum];//the following pointTrie(bool terminal = false, int num = 1):terminal(terminal), num(num){for (int i = 0; i < sonnum; ++i)son[i] = NULL;}
};
Trie* BuildTrie()// create a new node
{Trie *root=new Trie(false, 1);return root;
}
void Insert(Trie* root, string& s)// insert a new word to Trie tree
{for(int i=0; i<s.length(); ++i){if(root->son[s[i]-base] == NULL)root->son[s[i]-base]=new Trie(false,1);else root->son[s[i]-base]->num++;root=root->son[s[i]-base];}root->terminal=true;
}
void Delete(Trie *root)// delete the whole tree
{if(root!=NULL){for(int i=0;i<sonnum;++i)if(root->son[i]!=NULL)Delete(root->son[i]);delete root; root=NULL;}
}
Trie* Find(Trie *root,string& s)//trie to find the current word
{for(int i=0;i<s.length();++i)if(root->son[s[i]-base]!=NULL)root=root->son[s[i]-base];else return NULL;return root;
}
void ListAll(Trie *root,string& cur)
{if (root->terminal)cout << cur << endl;for (int i = 0; i < sonnum; ++i)if (root->son[i]) {     string tmp = "a";tmp[0] += i;string next = cur + tmp;ListAll(root->son[i], next);		  }
}int main() {Trie* trie = BuildTrie();string str[] = {"abc", "ab", "ade", "ace"};for (int i = 0; i < 4; ++i)Insert(trie, str[i]);string s = "ab";Trie *searchWord = Find(trie, s);ListAll(searchWord, s);		return 0;
}

Python Version:

class Node:def __init__(self, terminal = False, num = 0):self.terminal = Falseself.num = numself.son = {}def BuildTrie():root = Node(False, 0)return rootdef Insert(root, s):root.num += 1for c in s:if (c in root.son):root = root.son[c]root.num += 1else:root.son[c] = Node(False, 1)root = root.son[c]root.terminal = Truedef IsExist(root, s):for c in s:if (c in root.son):root = root.son[c]else:return Falsereturn root.terminalif __name__ == '__main__':root = BuildTrie()for item in ["abc", "ab", "ade", "ace"]:Insert(root, item)print(IsExist(root, "abc"))print(IsExist(root, "abcd"))

 

 

 

 

 

 

 

这篇关于CareerCup Trie Prefix Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/819416

相关文章

树(Tree)——《啊哈!算法》

树 什么是树?树是一种特殊的图,不包含回路的连通无向树。 正因为树有着“不包含回路”这个特点,所以树就被赋予了很多特性。 一棵树中的任意两个结点有且仅有唯一的一条路径连通。一棵树如果有n个结点,那么它一定恰好有n-1条边。在一棵树中加一条边将会构成一个回路。 一棵树有且只有一个根结点。 没有父结点的结点称为根结点(祖先)。没有子结点的结点称为叶结点。如果一个结点既不是根结点也不是叶

226 Invert Binary Tree

//226 Invert Binary Tree//算法思路:主要使用递归算法public class Solution {public TreeNode invertTree(TreeNode root) {//1 出口 空节点if (root==null)return null;//2 递归 调用自己TreeNode left = root.left;TreeNode right = ro

Sorry!Hbase的LSM Tree就是可以为所欲为!

我们先抛出一个问题: LSM树是HBase里使用的非常有创意的一种数据结构。在有代表性的关系型数据库如MySQL、SQL Server、Oracle中,数据存储与索引的基本结构就是我们耳熟能详的B树和B+树。而在一些主流的NoSQL数据库如HBase、Cassandra、LevelDB、RocksDB中,则是使用日志结构合并树(Log-structured Merge Tree,LSM Tr

【spring】does not have member field ‘com.sun.tools.javac.tree.JCTree qualid

spring-in-action-6-samples 的JDK版本 最小是11,我使用 了22: jdk21 jdk22 都与lombok 不兼容,必须使用兼容版本, 否则报错: thingsboard 的大神解释了: java: java.lang.NoSuchFieldError: Class com

Python高效实现Trie(前缀树)及其插入和查找操作

Python高效实现Trie(前缀树)及其插入和查找操作 在Python面试中,考官通常会关注候选人的编程能力、问题解决能力以及对Python语言特性的理解。Trie(前缀树)是一种高效的数据结构,广泛应用于字符串处理、自动补全、拼写检查等场景。本文将详细介绍如何实现一个Trie,并提供插入和查找操作,确保代码实用性强,条理清晰,操作性强。 1. 引言 Trie(前缀树)是一种树形数据结构,

[LeetCode] 863. All Nodes Distance K in Binary Tree

题:https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/ 题目大意 求给树中,距给定 结点 指定长度的 所有结点的val 思路 tree -> graph 、 bfs 先遍历树,并用map记录每个结点的父结点 ,将树变为图,然后 bfs。 /*** Definition for a binary tree

js实现树级递归,通过js生成tree树形菜单(递归算法)

1、效果图 需求:首先这是一个数据集—js的类型,我们需要把生成一个tree形式的对象 : var data = [{ id: 1, name: "办公管理", pid: 0 },{ id: 2, name: "请假申请", pid: 1 },{ id: 3, name: "出差申请", pid: 1 },{ id: 4, name: "请假记录", pid: 2 },{ id:

【unity实战】利用Root Motion+Blend Tree+Input System+Cinemachine制作一个简单的角色控制器

文章目录 前言动画设置Blend Tree配置角色添加刚体和碰撞体代码控制人物移动那么我们接下来调整一下相机的视角效果参考完结 前言 Input System知识参考: 【推荐100个unity插件之18】Unity 新版输入系统Input System的使用,看这篇就够了 Cinemachine虚拟相机知识参考: 【推荐100个unity插件之10】Unity最全的最详细的C

树链剖分 + 后缀数组 - E. Misha and LCP on Tree

E. Misha and LCP on Tree  Problem's Link   Mean:  给出一棵树,每个结点上有一个字母。每个询问给出两个路径,问这两个路径的串的最长公共前缀。 analyse: 做法:树链剖分+后缀数组. 记录每条链的串,正反都需要标记,组成一个长串. 然后记录每条链对应的串在大串中的位置,对大串求后缀数组,最后询问就是在一些链

数据结构 - Codeforces Round #353 (Div. 2) D. Tree Construction

Tree Construction  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定n个数,按照构造Binary Search Tree的方式来构造BST树,按顺序输出每一个非root结点的父节点的值。 analyse