char* convert(char* s, int numRows) {
char str[numRows+1][1000];
int i=0,j=0,n,p=0,flag=0;//p记录现在填充到s的第几个字符了
n=strlen(s);
char *str2;
str2=(char *)malloc((n+1)*sizeof(char));
while(p<n)
{
if(numRows>1)flag=flag%(numRows-1);
else flag=0;
j++;//一列一列填入数字
if(flag==0)//“之”的首末要全部填上
{
if(n-p>=numRows)//剩余的字符可以填满
{
for(i=1;i<=numRows;i++)
str[i][j]=s[p++];
}
else
{
int q=n-p+1;
for(i=1;i<=q;i++)
str[i][j]=s[p++];
for(i=q;i<=numRows;i++)
{
str[i][j]=' ';
}
}
}
else//每一列只需要填一个字符
{
for(i=1;i<=numRows;i++)
{
if(i==(numRows-flag))
{
str[i][j]=s[p++];
}
else
{
str[i][j]=' ';
}
}
}
flag++;
}
n=j;//共j列
p=0;
for(i=1;i<=numRows;i++)
{
for(j=1;j<=n;j++)
{
if(str[i][j]!=' ')
{
str2[p]=str[i][j];p++;
}
}
}
str2[p]='\0';
return str2;
}
更优的sample:
char* convert(char* s, int numRows) {
if (numRows == 1) return s;
else if (numRows == 0) return NULL;
int len = strlen(s);
int i;
int ind[10000];
char ret[10000] = {0};
//int *ind = (int*)malloc(sizeof(int) * len);
//char *ret = (char*)malloc(sizeof(char) * (len+1));
int mod = numRows*2-2;
int index = 0;
for (i = 0;i < numRows;i++){
int count = i;
if (i != 0 && i != numRows-1){
while(count<len){
ind[count] = index++;
count = count + mod - i - i;
if (count >= len) break;
ind[count] = index++;
count = count + i + i;
}
}
else {
while(count<len){
ind[count] = index++;
count += mod;
}
}
}
for (i = 0;i<len;i++){
ret[ind[i]] = s[i];
}
strcpy(s, ret);
//free(ret);
//free(ind);
return s;
}