Skip to content

Commit 2d839a6

Browse files
authored
Create 0290-Word-Pattern.c
Create the C solution as the same solution in the YouTube video "https://www.youtube.com/watch?v=W_akoecmCbM"
1 parent 6a4e00c commit 2d839a6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

c/0290-Word-Pattern.c

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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

Comments
 (0)