Share my c code, hope it's not the worst one


  • 0
    K

    bool wordPattern(char* pattern, char* str) {

    char *pattern_set[26];
    int i;
    
    for (i = 0; i < 26; i++) {
        pattern_set[i] = (char*)malloc(sizeof(char) * 100);
        pattern_set[i][0] = '\0';
    }
    
    while (*pattern != '\0') {
        char pat_str[100] = "\0";
        char *p;
        int idx = *pattern - 'a';
        
        while (*str != '\0' && *str == ' ') str++;
        p = str;
        while (*str != '\0' && *str != ' ') str++;
        
        if (p == str) {
            break;
        }
        else {
            memcpy(pat_str, p, str - p);
            
            if (pattern_set[idx][0] == '\0') {
                strcpy(pattern_set[idx], pat_str);
            }
            else if (strcmp(pat_str, pattern_set[idx]) != 0) {
                break;
            }
    
            for (int d = 0; d < 26; d++) {
                if (d != idx && strcmp(pat_str, pattern_set[d]) == 0)
                    return false;
            }
        }
    
        pattern++;
    }
    
    for (i = 0; i < 26; i++)
        free(pattern_set[i]);
    
    while (*str != '\0' && *str == ' ') str++;
    
    return *pattern == '\0' && *str == '\0';
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.