#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct TrieNode_t { char data; short int end_flag;//字符串完全添加标志位 struct TrieNode_t* child_node[26]; } TrieNode; TrieNode root = { 0 }; //添加字符串到树中 void InsertString(char a[], int len) { int i; TrieNode *p = &root; for (i = 0; i < len; i++) { int index = a[i] - 'a'; if (p->child_node[index] == 0) { TrieNode *p_child = (TrieNode *)malloc(sizeof(struct TrieNode_t)); if (NULL == p_child) { printf("malloc fail "); return; } p_child->data = a[i]; p->child_node[index] = p_child; } p = p->child_node[index]; } p->end_flag = 1; } //查询字符串,时间复杂度为O(len) int SearchString(TrieNode root, char a[], int len) { int i; TrieNode *p = &root; for (i = 0; i < len; i++) { int index = a[i] - 'a'; if (p->child_node[index] == 0) { return -1; } p = p->child_node[index]; } if (p->end_flag == 1) { return 0; } else { return -1; } } int main() { char a[10] = "helloworld"; char b[10] = "gelloworld"; char c[10] = "helltworld"; char d[10] = "helloworlr"; char e[5] = "hello"; InsertString(a, 10); printf("%d ", SearchString(root, e, 10)); return 0; }