力扣原题:
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
我的代码如下:
char * convert(char * s, int numRows){
int i=0;
int j=0;
int k=0;
int len=strlen(s);
char *receive;
receive=(char*)malloc(len+numRows); //
int row[strlen(s)+numRows];
if(numRows==1)
return s;
if(numRows==2)
{
for(i=0;i<len;i=i+2)
receive[i/2]=s[i];
for(i=1;i<len;i=i+2)
receive[i/2+1]=s[i];
return receive;
}
//行号数组
for(i=0;i<len;i=i+2*numRows-2) //确定下一个循环的范围
{
for(j=i,k=j+2*numRows-2;j!=k;j++,k--) //从两端向中心赋值
{
int count=0;
row[j]=count;
row[k]=row[j];
}
}
row[len]='\0';
//生成新字符串
for(i=0;i<numRows;i++) //取一个行号
{
for(j=0;j<strlen(s);j++) //找到该行元素
{
if(row[j]=i)
{
char temp[2]={s[j]};
strcat(receive,temp); //将该行元素连接到字符串后
}
}
}
receive[len]='\0';
return receive;
}
运行后提示:
求各位帮我找到问题并垂与斧正,感谢。