Trie树
Trie树形状如图-->
应用场景-->
典型应用是用于统计,排序和保存大量的字符串(不仅限于字符串),经常被搜索引擎系统用于文本词频统计
代码-->java
public class Main { private int SIZE = 26; private TrieNode root; public static void main(String[] args) { Main main = new Main(); String[]strs= {"banana","band","bee","absolute","acm",}; String[]prefix= {"ba","b","band","abc",}; for (String str : strs) { main.insert(str); } main.preTraverse(main.root); System.out.println("\n"+main.has("abc")); if (main.has("abc")) { System.out.println(main.has("abc")); } else { main.insert("abc"); System.out.println(main.has("abc")); } } public Main() { root = new TrieNode(); } public void insert(String str) { if (str==null || str.length() == 0) { return ; } TrieNode node = root; char[] letters = str.toCharArray(); for (int i = 0,len = str.length(); i < len; i++) { int pos = letters[i] -'a'; if (node.sonNodes[pos] == null) { node.sonNodes[pos] = new TrieNode(); node.sonNodes[pos].val = letters[i]; } else { node.sonNodes[pos].num++; } node = node.sonNodes[pos]; } node.isEnd = true; } public boolean has(String str) { if (str==null||str.length()==0) { return false; } TrieNode node = root; char[] letters = str.toCharArray(); for (int i = 0,len = str.length(); i < len; i++) { int pos = letters[i] - 'a'; if (node.sonNodes[pos]!=null) { node = node.sonNodes[pos]; } else { return false; } } return node.isEnd; } public void preTraverse(TrieNode node) { if(node!=null) { System.out.print(node.val+"-"); for(TrieNode child:node.sonNodes) { preTraverse(child); } } } class TrieNode { private int num; private TrieNode[] sonNodes; private boolean isEnd; private char val; TrieNode() { num=1; sonNodes = new TrieNode[SIZE]; isEnd = false; } } }
代码-->c#
#include<iostream> #include<string> using namespace std; struct trieNode{ int count;//统计单词前缀出现的次数 trieNode* next[26];//指向各子树的指针 bool exit;//标记该结点处是否构成单词 trieNode():count(0),exit(false){ for (int i = 0; i < 26; i++){ next[i] = NULL; } } }; void trieInsert(trieNode* root, string &word){ trieNode *node = root; int id; int len = word.size(); int i = 0; while (i < len){ id = word[i]-'a'; if (node->next[id] == NULL){ node->next[id] = new trieNode(); } node = node->next[id]; node->count += 1; i++; } node->exit = true;//单词结束,可以构成一个单词 } int trieSearch(trieNode*root, string &word){ trieNode* node = root; int len = word.size(); int i = 0; while (i < len){ int id = word[i] - 'a'; if (node->next[id] != NULL){ node = node->next[id]; i++; } else{ return 0; } } return node->count; } int main() { trieNode *root = new trieNode(); string word; int flag = false; while (getline(cin, word)){ if (flag){ cout << trieSearch(root, word) << endl; } else{ if (!word.empty()){ trieInsert(root, word); } else{ flag = true; } } } return 0; }