题目:
题解:
typedef struct node_t
{
char *key;
char *value;
struct node_t* pnext;
}NODE_T;
typedef struct hash_t
{
NODE_T** hash_list;
int size;
}HASH_T;
HASH_T *hash_init(int size)
{
HASH_T *hash = (HASH_T *)malloc(sizeof(HASH_T));
if(NULL == hash)
{
printf("open space error!");
exit(0);
}
hash->hash_list = NULL;
hash->size = size;
hash->hash_list = (NODE_T **)calloc(size, sizeof(NODE_T *));
if(NULL == hash->hash_list)
{
printf("open space error!");
exit(0);
}
for(int i = 0; i < size; i++)
{
hash->hash_list[i] = (NODE_T *)calloc(size, sizeof(NODE_T));
if(NULL == hash->hash_list[i])
{
printf("open space error!");
exit(0);
}
}
return hash;
}
int hash_pos(HASH_T *hash, char *key) // 返回当前键值所在链表
{
return key[0] % hash->size;
}
NODE_T* hash_find(HASH_T *hash, char *key) // 返回值在链表的节点
{
int pos = hash_pos(hash, key);
NODE_T *now_node = hash->hash_list[pos]->pnext;
while(now_node != NULL && strcmp(now_node->key, key))
{
now_node = now_node->pnext;
}
return now_node;
}
bool hash_put(HASH_T *hash, char *key, char *value) // 比对键值信息,未找到新建节点存储键值
{
NODE_T *now_node = hash_find(hash, key);
NODE_T *new_node = NULL;
if(NULL == now_node)
{
new_node = (NODE_T*)malloc(sizeof(NODE_T));
if(NULL == new_node)
{
printf("open space error!");
exit(0);
}
new_node->key = (char*)malloc(sizeof(char) * (strlen(key) + 1));
if(NULL == new_node->key)
{
printf("open space error!");
exit(0);
}
strcpy(new_node->key, key);
new_node->value = (char*)malloc(sizeof(char) * (strlen(value) + 1));
if(NULL == new_node->value)
{
printf("open space error!");
exit(0);
}
strcpy(new_node->value, value);
new_node->pnext = hash->hash_list[hash_pos(hash, key)]->pnext;
hash->hash_list[hash_pos(hash, key)]->pnext = new_node;
}
else
{
if(0 != strcmp(now_node->value, value))
{
return false;
}
}
return true;
}
bool wordPattern(char* s, char* pattern) {
HASH_T *pattern_hash = hash_init(26);
HASH_T *s_hash = hash_init(26);
char *str_pattern = NULL, *str_s = NULL; // 用于存放值
int *pattern_count = NULL; // 存放每个单词所处下标
int i = 0, count = 0, pattern_len = strlen(pattern), s_len = strlen(s); // 用于轮询数组,数组长度
str_pattern = (char *)calloc(pattern_len + 1, sizeof(char)); // 分配值空间
if(NULL == str_pattern)
{
printf("open space error!");
exit(0);
}
str_s = (char *)calloc(2, sizeof(char));
if(NULL == str_s)
{
printf("open space error!");
exit(0);
}
pattern_count = (int *)calloc(pattern_len, sizeof(int));
if(NULL == pattern_count)
{
printf("open space error!");
exit(0);
}
pattern_count[count++] = 0; // 添加第一个下标
for(i = 0; i < pattern_len; i++) // 替换空格,用于strcpy来拷贝单词
{
if(' ' == pattern[i])
{
pattern_count[count++] = i + 1; // 下一个单词起始位置
pattern[i] = '\0';
}
}
if(s_len != count) // 单词数不一致退出
{
return false;
}
for(i = 0; i < s_len; i++)
{
strcpy(str_pattern, &pattern[pattern_count[i]]); // 放入当前比对值
str_s[0] = s[i];
if(!hash_put(pattern_hash, str_pattern, str_s) ||
!hash_put(s_hash, str_s, str_pattern))
{
return false;
}
}
return true;
}