290. 单词规律
C代码:别人手搓的
bool wordPattern(char * pattern, char * s){
char arr[301][3001];
char *p = strtok(s, " ");
int pos = 0;
while(p != NULL) {
sprintf(arr[pos++], "%s", p);
p = strtok(NULL, " ");
}
int len = strlen(pattern);
if(len != pos) {
return false;
}
for(int i = 0; i < len; i++) {
for(int j = i + 1; j < len; j++) {
int re = strcmp(&arr[i][0], &arr[j][0]);
if((pattern[i] == pattern[j] && re != 0) || (pattern[i] != pattern[j] && re == 0)) { // 双向绑定!
return false;
}
}
}
return true;
}
C代码:自己手搓的
// 左边结构是对称的
// 应该是根据patttern去查找字符串,再与s中的字符串进行对比;双向绑定!
// "abba" "aaaa"
// "dog dog dog dog" "dog cat cat dog"
typedef struct {
char ch;
char* str;
UT_hash_handle hh;
} HashTable;
HashTable* head1;
HashTable* head2;
void addHash1(char * pattern, char** arr, int len1) {
HashTable* out = NULL;
for(int i = 0; i < len1 / 2; ++i) {
HASH_FIND(hh, head1, &pattern[i], sizeof(char), out);
if (NULL == out) {
out = (HashTable*)malloc(sizeof(HashTable));
out->ch = pattern[i];
out->str = arr[i];
HASH_ADD(hh, head1, ch, sizeof(char), out);
}
}
}
void addHash2(char * pattern, char** arr, int len1) {
HashTable* out = NULL;
for(int i = 0; i < len1 / 2; ++i) {
out = NULL;
HASH_FIND_STR(head2, &arr[i][0], out);
if (NULL == out) {
out = (HashTable*)malloc(sizeof(HashTable));
out->ch = pattern[i];
out->str = arr[i];
HASH_ADD_STR(head2, str, out);
}
}
}
bool wordPattern(char * pattern, char * s){
int len1 = strlen(pattern);
int len2 = strlen(s);
// 将s中的字符串放入数组中
char** arr = (char**)malloc(sizeof(char*) * 1501);
int arrTop = 0;
char* str = strtok(s, " ");
while (str != NULL) {
arr[arrTop++] = str;
str = strtok(NULL, " ");
}
if (len1 != arrTop) {
return false;
}
// 放入hash
head1 = NULL;
head2 = NULL;
addHash1(pattern, arr, len1);
addHash2(pattern, arr, len1);
// 进行读取、判断
HashTable* out1 = NULL;
HashTable* out2 = NULL;
for(int i = len1 / 2; i < len1; ++i) {
HASH_FIND(hh, head1, &pattern[i], sizeof(char), out1);
HASH_FIND_STR(head2, &arr[i][0], out2);
if (NULL != out1 && strcmp(out1->str, arr[i]) != 0 || NULL != out2 && out2->ch != pattern[i]) {
return false;
}
}
return true;
}