#include #include #include #define ALPHABET_SIZE 26 #define MAX_LENGTH 100 struct TreeNode { char character; struct TreeNode *children[ALPHABET_SIZE]; }; struct TreeNode *createNode(char c) { struct TreeNode *newNode = (struct TreeNode*) malloc(sizeof(struct TreeNode)); if(!newNode) { printf("Error\n"); exit(1); } newNode -> character = c; for(int i = 0; i < ALPHABET_SIZE; i++) newNode -> children[i] = NULL; return newNode; } struct TreeNode *createTrie(char *fileName) { struct TreeNode *root = createNode(' '); char word[MAX_LENGTH]; FILE *f = fopen(fileName, "r"); int index; while((fscanf(f, "%s", word)) != EOF) { struct TreeNode *pom = root; for(int i = 0; i < strlen(word); i++) { if (word[i] < 'A' && word[i] > 'z') { printf("Invalid character [%c]\n", word[i]); exit(1); } // A-Z a-z if (word[i] >= 'A' && word[i] <= 'Z') word[i] += 32; index = word[i] - 'a'; if (pom -> children[index] == NULL) { pom -> children[index] = createNode(word[i]); } pom = pom -> children[index]; } } fclose(f); return root; } int wordExists(struct TreeNode *root, char *word) { struct TreeNode *pom = root; for(int i = 0; i < strlen(word); i++) { int index = word[i] - 'a'; if(pom -> children[index] == NULL) return 0; pom = pom -> children[index]; } return 1; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage %s \n", argv[0]); exit(1); } struct TreeNode *root = createTrie(argv[1]); char word[MAX_LENGTH]; scanf("%s", word); if(wordExists(root, word)) { printf("DA\n"); } else { printf("NE\n"); } return 0; }