[leetcode] -6 ZigZag Conversion

zigzag pattern 即之字型,字母“Z”型,convert函数要求将一个Z字形按列读取的字符串转换为按行读取的字符串。

基本思路是按行顺序读取并存入结果字符串,总行数为min(nRows,len),nRows为Z字的行数,len为源字符串的总长度。

下面用图来说明:


行数k=1,nRows时,读取第一个字符后,下一个字符与当前字符在源字符串中的距离为step = 2(nRows-1),依次重复

1<k<nRows时,读取第一个字符后,下一个字符与当前字符在源字符串中的距离为step1 = 2(nRows-k),下一个字符与下下个字符在源字符串中的距离为step2 = 2(k-1),如此以step1,step2进行重复

char* convert(char* s, int numRows) {
	int len = strlen(s);
	int num = 0, i, step1,step2,step, index;
	char *res = (char *)malloc((len+1)*sizeof(char));
	for(i = 1; i <= numRows && i <= len; ++ i){
		index = i;
		if(i == 1 || i == numRows){
			step = 2 * numRows - 2;
			while(index <= len){
				res[num] = s[index-1];
				num ++;
				index += step;
			}
		}else{
			step1 = 2*(numRows - index);
			step2 = 2*(index - 1);
			while(index <= len){
				res[num] = s[index-1];
				num ++;
				index += step1;
				if(index <= len){
					res[num] = s[index-1];
					num ++;
				}
				index += step2;
			}
		}
	}
	res[len] = '\0';
	return res;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值