1. 程式人生 > >Leetcode Z字形變換

Leetcode Z字形變換

題目描述:

將字串 "PAYPALISHIRING" 以Z字形排列成給定的行數:

P   A   H   N
A P L S I I G
Y   I   R

之後從左往右,逐行讀取字元:"PAHNAPLSIIGYIR"

實現一個將字串進行指定行數變換的函式:

string convert(string s, int numRows);

示例 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

思路:

參考 

觀察示例可知,往下走要走numRows步,往上走要走numRows-2步(除去頭尾,因為和往下走重疊)
模擬Z字遍歷字串

  1. 往下走numRows步
  2. 往上走numRows-2步
  3. 重複1,2直到字串遍歷結束

C++程式碼:

class Solution {
public:
	string convert(string s, int numRows) {
		if (numRows < 2) // 一行或者空行,返回本身
			return s;

		vector<string> vec(numRows);  // vec[0]:z字型的第0行字串;vec[1]:第1行

		int index = 0, len = s.size(); // index:s字串索引
		string curr_char;
		while (index < len){  // 遍歷字串s
			for (int row = 0; row < numRows && index < len; row++) {// 往下走4步
				curr_char = s[index];
				vec[row].append(curr_char);
				index++;
			}
			for (int row = numRows - 2; row > 0 && index < len; row--){ // 往下走2步
				curr_char = s[index];
				vec[row].append(curr_char);
				index++;
			}
		}

		// 二維變一維,拼接在第0行後面, 以便返回輸出
		for (int row = 1; row < numRows; row++) // 把其他行,拼接在0行的後面
			vec[0].append(vec[row]);

		return vec[0];
	}
};

說明:vec[0]: 儲存是string字串,即第0行分別是圖例中的1,7;vec[1]儲存的是第1行,即1,6,8,12;