LeeteCode 6字符串Z型变换

用最原始的方法
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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值