概述
题目:
/**题目:6. Z字形变换(题目地址:https://leetcode-cn.com/problems/zigzag-conversion/description/)
* 将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
* P A H N
* A P L S I I G
* Y I R
* 之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
* 示例 1:
* 输入: s = "PAYPALISHIRING", numRows = 3
* 输出: "PAHNAPLSIIGYIR"
* 示例 2:
* 输入: s = "PAYPALISHIRING", numRows = 4
* 输出: "PINALSIGYAHRPI"
* 解释:
* P I N
* A L S I G
* Y A H R
* P I
*/
用了一个简单的方法,实现起来最简单,比较容易理解吧。我的思路是:
我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/**题目:6. Z字形变换
* 将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
* P A H N
* A P L S I I G
* Y I R
* 之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
* 示例 1:
* 输入: s = "PAYPALISHIRING", numRows = 3
* 输出: "PAHNAPLSIIGYIR"
* 示例 2:
* 输入: s = "PAYPALISHIRING", numRows = 4
* 输出: "PINALSIGYAHRPI"
* 解释:
* P I N
* A L S I G
* Y A H R
* P I
*/
char* convert(char* s, int numRows)
{
char flag = '#';
int length = strlen(s);
int nz = 2*numRows - 2;
int nx = length/nz + ((length%nz>0)?1:0);
//printf("%d, %d, %d, %dn",length,numRows,nx,nz);
printf("Length of "%s" is %d.n",s,length);
int nz2 = nz + 1;
int L = nz2 * nx;
char *str = malloc(sizeof(char)*(L+1));
int i, ix, iz;
for(i=0;i<length;i++)
{
ix = i/nz;
iz = i%nz;
str[ix*nz2 + iz] = s[i];
}
for(i=0;i<nx-((length%nz>0)?1:0);i++)
{
str[i*nz2+nz] = flag;
}
for(i=nz2*(nx-((length%nz>0)?1:0))+length%nz;i<L;i++)
{
str[i] = flag;
}
str[L] = '