LeetCode之6. Z 字形变换

LeetCode之6. Z 字形变换

  1. 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
    比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:

在这里插入图片描述
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

在这里插入图片描述

代码如下:

class Solution {
public:
    string convert(string s, int numRows) {
		char **buf= new char*[numRows];
		int length = s.length();
		int numCols = getCols(length,numRows);

		for (int i = 0; i < numRows; i++)
		{
			buf[i] = new char[numCols];
		}
	
		for (int i = 0; i < numRows; i++)
		{
			for (int j = 0; j < numCols; j++)
			{
				buf[i][j] = '\0';
			}
		}

		////////////////////////////////////////////////////////////////
		int count = 0;
		int t = numRows - 1>0?numRows-1:1;
		for (int m = 0; m < numCols; m++)
		{
			//偶数
			if (m%t==0)
			{
				for (int n = 0; n < numRows; n++)//就是rows没错
				{
					if (count>length)
					{
						break;
					}
					buf[n][m] = s[count++];
				}
			}
			else//奇数
			{
				for (int j = numRows - 2, k = m; j>0 && count<length; k++, j--)
				{
					buf[j][k] = s[count++];
				}
				m += t-1;
				m--;
			}
			
		}

		string ret;
		for (int i = 0; i < numRows; i++)
		{
			for (int j = 0; j < numCols;j++)
			{
				if (buf[i][j]!='\0')
				{
					ret.append(1, buf[i][j]);
				}
			}
		}
		return ret;
	}

	int getCols(int s,int n){
		int i = 0;
		int t = n - 1>0?n-1:1;
		int ts = 0;
		for (i = 0; ts < s;i++)
		{
			if (i%t==0)
			{
				ts += n;
			}
			else
			{
				ts++;
			}
		}

		return i;
	}
};

6. Z 字形变换

猜你喜欢

转载自blog.csdn.net/wu_lian_nan/article/details/84331004
今日推荐