forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0929-unique-email-addresses.c
53 lines (47 loc) · 1.12 KB
/
0929-unique-email-addresses.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Represent an element in a hash table.
typedef struct Hash {
char* key;
UT_hash_handle hh;
} Hash;
char *EmailToKey(char *email) {
int len = strlen(email);
char *key = (char*)malloc( len + 1);
char *k = key;
int domain = 0;
int i;
for (i = 0; i < len; i++) {
if (!domain && email[i] == '.') {
continue;
}
if (email[i] == '+') {
while(i < len && email[i] != '@') {
i++;
}
}
if (email[i] == '@') {
domain = 1;
}
*k++ = email[i];
}
*k = '\0';
return key;
}
int numUniqueEmails(char ** emails, int emailsSize){
Hash *root = NULL;
Hash *entry = NULL;
char *key = NULL;
int i;
for (i = 0; i < emailsSize; i++) {
entry = NULL;
key = EmailToKey(emails[i]);
HASH_FIND_STR(root, key, entry);
if (!entry) {
entry = malloc(sizeof(Hash));
entry->key = key;
HASH_ADD_KEYPTR(hh, root, key, strlen(key), entry);
} else {
free(key);
}
}
return HASH_COUNT(root);
}