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 字形變換

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章