用最原始的方法
1.先把字符串转换成N行2维数组,按照规律存入二维数组
2.然后对二维数组 遍历,存到目标字符串
3:注意素组越界访问和边界值的设定
这个方法比较笨。执行的效率不高
#define MAX_SIZE 1000
char** ConvertToMatrix(char* s,int numRows)
{
char** strmatrix = (char**)malloc(sizeof(char*) * (numRows+1));
for (int i = 0; i <= numRows; i++) {
strmatrix[i] = (char*)malloc(sizeof(char) * strlen(s) * 4);
}
int len = strlen(s);
int numcols = (len / numRows == 0) ? 1 : (numRows * len / numRows);
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numcols; j++)
{
strmatrix[i][j] = '-';
}
}
int count = 0;
for (int col = 0; col < numcols; col++) {
if ((col % (numRows - 1)) == 0) {
for (int row = 0; (row < numRows) && (count< len); row++) {
strmatrix[row][col] = s[count];
count++;
}
}
else {
for (int row = numRows - 1; (row >= 0) && (count < len); row--) {
if ((row + col ) == ((numRows-1) + (numRows-1) * (col/(numRows-1)))) {
strmatrix[row][col] = s[count];
count++;
}
}
}
}
return strmatrix;
}
char * convert(char * s, int numRows)
{
//Convert string to matrix
char** strmatrix = (char**)malloc(sizeof(char*) * MAX_SIZE);
//memset(strmatrix, '-', MAX_SIZE);
char* res = (char*) malloc (sizeof(char*) * MAX_SIZE);
int count = 0;
res[0] = '\0';
int len = strlen(s);
int numcols = (len / numRows == 0) ? 1 : (numRows * len / numRows);
if (numRows == 1) {
return s;
}
strmatrix = ConvertToMatrix(s, numRows);
for (int i = 0; i < numRows; i++) {
for (int j = 0; j <numcols; j++) {
if (strmatrix[i][j] != '-') {
res[count] = strmatrix[i][j];
count++;
}
//printf_s("%c", strmatrix[i][j]);
}
//printf_s("\n");
}
res[count] = '\0';
//convert matrix to string again.
return res;
}
更加优化的算法是找规律,找出字符串下表的规律。
第一行比肩容易找 2n-2
但是对角线线上的值规律不一样: 对角线上 为2n-2 = n-i(i为行数),参考别人的思路:代码如下:
int len = strlen(s);
if (numRows <= 1)
return s;
char *t = (char *)malloc(sizeof(char) * (len + 1));
int numSize = 0;
int n = 2 * numRows - 2;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < len; j++)
{
int k = j % n;
if (k == i || k == n - i)
{
t[numSize++] = s[j];
}
}
}
t[numSize] = '\0';
return t;