Untitled

 avatar
unknown
plain_text
a year ago
2.0 kB
4
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct TrieNode {
    char key[50];
    int count;
    struct TrieNode* children[256];
};

struct TrieNode* createNode() 
{
    struct TrieNode* newNode = (struct TrieNode*)malloc(sizeof(struct TrieNode));
    newNode->count = 0;
    memset(newNode->key, 0, sizeof(newNode->key));
    for (int i = 0; i < 256; i++)
    {
        newNode->children[i] = NULL;
    }
    return newNode;
}

void insert(struct TrieNode* head, char* str) {
    struct TrieNode* current = head;
    int length = strlen(str);
    for (int i = 0; i < length; i++) {
        unsigned char index = (unsigned char)str[i];
        if (current->children[index] == NULL) {
            current->children[index] = createNode();
        }
        current = current->children[index];
    }
    strncpy(current->key, str, sizeof(current->key) - 1);
    current->count++;
}

void preorAder(struct TrieNode* current, int* maxCount, char* maxKey) {
    if (current == NULL)
    {
        return;
    }

    if (current->count > *maxCount) 
    {
        *maxCount = current->count;
        strncpy(maxKey, current->key, sizeof(current->key) - 1);
    }

    for (int i = 0; i < 256; i++) 
    {
        preorder(current->children[i], maxCount, maxKey);
    }
}

int main() {
   
    char* words[] = {  "code", "coder", "coding", "codable", "codec", "codecs", "coded","codeless", "codec", "codecs", "codependence", "codex", "codify","codependents", "codes", "code" "coder", "codesign", "codec","codeveloper", "codrive", "codec", "codecs", "codiscovered"};
    struct TrieNode* head = createNode();
    for (int i = 0; i < sizeof(words) / sizeof(words[0]); i++)
    {
        insert(head, words[i]);
    }
    int maxCount = 0;
    char maxKey[50] = {0};
    preorder(head, &maxCount, maxKey);
    printf("Word : %s\n", maxKey);
    printf("Count: %d\n", maxCount);
    free(head);
    return 0;
}
Editor is loading...