struct TrieNode { int Count;<span style="white-space:pre"> </span>//前缀单词出现次数 struct TrieNode* Next[26];<span style="white-space:pre"> </span>//26个字母节点 }Tree,*Trie; TrieNode *root; void Create() //初始化 { root = new TrieNode; memset(root->Next,NULL,sizeof(root->Next)); root->Count = 0; } void Insert(char *s) //插入字符串s[],O(M*L) { TrieNode *p, *q; p = root; while(*s) { if(p->Next[*s-'a'] == NULL) { q = new TrieNode; memset(q->Next,NULL,sizeof(q->Next)); q->Count = 1; p->Next[*s-'a'] = q; } else p->Next[*s-'a']->Count++; p = p->Next[*s-'a']; s++; } } int Find(char *s) //查找字符串s[] O(N*L) { TrieNode *p, *q; p = root; while(*s) { if(p->Next[*s-'a'] == NULL) return 0; p = p->Next[*s-'a']; s++; } return p->Count; }
时间: 2024-11-02 23:38:03