|
| 1 | +typedef struct charToWord { |
| 2 | + int ch; /* we'll use this field as the key */ |
| 3 | + char* word; |
| 4 | + UT_hash_handle hh; /* makes this structure hashable */ |
| 5 | +}charToWord; |
| 6 | + |
| 7 | +typedef struct wordToChar { |
| 8 | + char* word; /* we'll use this field as the key */ |
| 9 | + int ch; |
| 10 | + UT_hash_handle hh; /* makes this structure hashable */ |
| 11 | +}wordToChar; |
| 12 | + |
| 13 | +bool wordPattern(char * pattern, char * s){ |
| 14 | + charToWord* charToWordMap = NULL; |
| 15 | + wordToChar* wordToCharMap = NULL; |
| 16 | + char* word = NULL; |
| 17 | + |
| 18 | + // Get the first word |
| 19 | + word = strtok(s, " "); |
| 20 | + |
| 21 | + for(size_t i = 0; i < strlen(pattern); i++) |
| 22 | + { |
| 23 | + charToWord* charToWordEntry = NULL; |
| 24 | + wordToChar* wordToCharEntry = NULL; |
| 25 | + int ch = pattern[i]; |
| 26 | + |
| 27 | + // If there is no words left (pattern > s) |
| 28 | + if(word == NULL) |
| 29 | + { |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + HASH_FIND_INT(charToWordMap, &ch, charToWordEntry); |
| 34 | + HASH_FIND_STR(wordToCharMap, word, wordToCharEntry); |
| 35 | + |
| 36 | + // If the char does exist in the map and the mapping is not the current word |
| 37 | + if(charToWordEntry && strcmp(charToWordEntry->word, word) != 0) |
| 38 | + { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + // If the word does exist in the map and the mapping is not the current char |
| 43 | + if(wordToCharEntry && wordToCharEntry->ch != ch) |
| 44 | + { |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | + /* Setup hash entries */ |
| 49 | + charToWordEntry = (charToWord*)malloc(sizeof(charToWord)); |
| 50 | + charToWordEntry->ch = ch; |
| 51 | + charToWordEntry->word = word; |
| 52 | + |
| 53 | + wordToCharEntry = (wordToChar*)malloc(sizeof(wordToChar)); |
| 54 | + wordToCharEntry->word = word; |
| 55 | + wordToCharEntry->ch = ch; |
| 56 | + |
| 57 | + /* Add entries to the hashes */ |
| 58 | + HASH_ADD_INT(charToWordMap, ch, charToWordEntry); |
| 59 | + HASH_ADD_STR(wordToCharMap, word, wordToCharEntry); |
| 60 | + |
| 61 | + // Move to the next word |
| 62 | + word = strtok(NULL, " "); |
| 63 | + } |
| 64 | + |
| 65 | + // If there is any words left (s > pattern) |
| 66 | + if(word != NULL) |
| 67 | + { |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + return true; |
| 72 | +} |
0 commit comments