Zigzag蛇形文字
题目
前几天刷leetcode的时候遇到一个有意思的题目,就是zigzag蛇形文字,就是将一个字符串以垂直蛇形的方式表现出来,但要给出水平的顺序。
核心
如果我们简化问题:把一个垂直排列的字符串算出水平的顺序,这样问题就很好解了,现在只是在字符串的中间插入一个字符,只需要计算出中间字符串在原串的位置即可。记住垂直串中第一行和最后一行是没有插入字符的。
题解
#include <string.h>
char* convert(char* s, int numRows) {
int lens = strlen(s);
char * res = malloc(lens + 1);
memset(res, 0x00, lens + 1);
int index = 0;
int zigSpan = numRows * 2 - 2;
if (numRows <= 1 || lens < 3 || lens < numRows) {
return s;
}
for (int i = 0; i < numRows; i++) {
for (int j = i; j < lens; j += zigSpan) {
res[index++] = s[j];
if (i != 0 && i != numRows - 1 && zigSpan + j - 2 * i < lens) {
res[index++] = s[zigSpan + j - 2 * i];
}
}
}
return res;
}
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char* res = convert("PAYPALISHIRING", 3);
printf("%s", res);
return EXIT_SUCCESS;
}