鄙人 刘天昊 csdn新用户 用博客来记录自己的学习过程也希望和网络上志同道合的朋友做一些交流
leetcode篇因为研究生本科都不是cs出生,所以自学数据结构,所有的leetcode都是C语言实现
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return
"PAHNAPLSIIGYIR"
.
者题目的意思希望最后的结果是z字形来读字符串的
什么意思呢?再举个例子
abcdefghijklmnopqrstuvwxyz 26个字母
nRows等于5
?例子我画图里了
然后我的方法先给每个字符标上数字,规律是先0递增到nRows-1再递减反复标到结尾。
然后把字符按照数字关键子存到哈希表中,发生冲突(处理冲突)用链表的结构把数链在后面。
最后访问哈希表把数按照顺序取出来,不过其实不用这么麻烦这是我的代码
typedef struct HashNode
{
int key;
char ch;
struct HashNode *next;
}HashNode;
typedef struct HashMap
{
int size;
HashNode **storage;
}HashMap;
HashMap *InitHash(int size)
{
HashMap *hashmap = (HashMap *)malloc(sizeof(HashMap));//定义结构体指针用来访问返回哈希表,并且为其动态申请内存
hashmap->size = size;//传入哈希表的大小
hashmap->storage = (HashNode **)calloc(size, sizeof(HashNode *));//定义一段连续的内存来存放一级指针(结构体node的地址)
return hashmap;//返回指向哈希表的指针
}
void HashSet(HashMap *hashmap, char ch, int key)
{
int addr = key;
HashNode *node;//定义结构体指针指向存放位置和关键字的结构体
HashNode *p;
if (node = hashmap->storage[addr])
{
while (node->next != NULL)
{
node = node->next;
}
p = (HashNode *)malloc(sizeof(HashNode));
p->ch = ch;
p->key = key;
p->next = NULL;
node->next = p;
}
else
{
node = (HashNode *)malloc(sizeof(HashNode));
node->ch = ch;
node->key = key;
node->next = NULL;
hashmap->storage[addr] = node;
}
}
char* convert(char* s, int numRows)
{
int len=strlen(s);
if(numRows==0)
{
exit(0);
}
if(numRows==1||numRows>=len)
{
return s;
}
if(len>numRows)
{
int ps=0;
int key=0;
int flag=0;
HashMap *hashmap;
HashNode *node;
hashmap=InitHash(numRows);
for(;ps<len;ps++)
{
if(key==0)
{
flag=0;
}
if(key==numRows-1)
{
flag=1;
}
if(flag==0)
{
HashSet(hashmap,*(s+ps),key);
key++;
}
if(flag==1)
{
HashSet(hashmap,*(s+ps),key);
key--;
}
}
int pt=0;
memset(s,0,len+1);
for(int i=0;i<numRows;i++)
{
node = hashmap->storage[i];
while (node != NULL)
{
*(s + pt) = node->ch;
node = node->next;
pt++;
}
}
return s;
}
exit(0);
}
最后这题很明显我的方法复杂了,希望大家可以讨论讨论大家共同进步,那么今天就到这里