#include <solution/290.h>
#include <stdlib.h>
#include <string.h>

char *foundValue(char **d, char k)
{
    int idx = k - 'a';
    return d[idx];
}

int foundKeyCount(char **d, char *v)
{
    int count = 0;
    for (int i = 0; i < 26; i++)
        if (d[i] && strcmp(v, d[i]) == 0)
            count++;

    return count;
}

void freeDict(char **d)
{
    for (int i = 0; i < 26; i++)
        free(d[i]);
    free(d);
}

int insertValue(char **d, char k, char *v)
{
    int idx = k - 'a';
    if (d[idx] != NULL)
        return -1;
    d[idx] = malloc(strlen(v) + 1);
    memcpy(d[idx], v, strlen(v) + 1);

    return foundKeyCount(d, v);
}

bool preCheck(char *p, char *s)
{
    int s_count = 0;
    for (; *s != '\0'; s++)
        if (*s == ' ')
            s_count++;
    return s_count + 1 == strlen(p);
}

bool wordPattern(char *pattern, char *s)
{
    if (!preCheck(pattern, s))
        return false;

    char **d = calloc(26, sizeof(char *));
    char *token = strtok(s, " ");

    for (int i = 0; i < strlen(pattern) && token != NULL; i++, token = strtok(NULL, " "))
    {
        switch (insertValue(d, pattern[i], token))
        {
        case 1:
            break;
        case -1:
            if (strcmp(token, foundValue(d, pattern[i])) == 0)
                break;
        default:
            freeDict(d);
            return false;
        }
    }

    freeDict(d);
    return true;
}
