题目来自力扣:
做之前我必须吐槽几句,这是我写过最难的题了!!!
下面是我的代码
别问为什么没有注释,我打代码从来不带注释,看得懂的才是同路人
char* convert(char* s, int numRows)
{
int sLenth = strlen(s);
printf("字符串的长度为:%d\n", sLenth);
char* output = (char*)malloc(1000);
memset(output, 0, 1000);
int subscript = 0;
int index = sLenth / (numRows + (numRows - 2));
index++;
for (int i = 0; i < index; i++)
{
output[i] = s[subscript];
subscript += numRows + (numRows - 2);
}
subscript = 0;
int num = 0;
int arrayLength = strlen(output);
int index2 = 1;
//numRows
for (int i = 0; i < numRows - 1; i++)
{
for (int j = 0; j < (index + (index - 1)) / 2 + 1; j++)
{
if (s[num + index2] != '\0')
{
printf("s[%d + %d] == %c\n", num, index2, s[num + index2]);
output[arrayLength++] = s[num + index2];
}
if (s[num + numRows + numRows - 2 - 1] != '\0')
{
printf("s[%d+%d+%d-2-%d] == %c\n",num,numRows,numRows,index2, s[num + numRows + numRows - 2 - index2]);
if ((num + index2) == (num + numRows + numRows - 2 - index2))
{
goto A;
}
output[arrayLength++] = s[num + numRows + numRows - 2 - index2];
}
A:;
printf("\n");
num += (numRows + numRows - 2);
}
num = 0;
index2++;
}
return output;
}
int main()
{
int numRows = 0;
char* s = (char*)malloc(1000);
int sLenth = strlen(s);
memset(s, 0, 1000);
printf("请用户输入字符串:");
scanf("%s", s);
while (getchar() != '\n');
printf("请用户输入行数:");
scanf("%d", &numRows);
if (numRows == 1)
{
printf("字形变化后的字符串为:");
printf("%s", s);
return 0;
}
char* op = convert(s, numRows);
printf("字形变化后的字符串为:");
for (int i = 0; i < sLenth; i++)
{
printf("%c", op[i]);
}
return 0;
}