日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C++中的Z字形變換問(wèn)題_C 語(yǔ)言

作者:ufgnix0802 ? 更新時(shí)間: 2022-09-01 編程語(yǔ)言

Z字形變換

描述

將一個(gè)給定字符串 s 根據(jù)給定的行數(shù) numRows ,以從上往下、從左到右進(jìn)行 Z 字形排列。

比如輸入字符串為 “PAYPALISHIRING” 行數(shù)為 3 時(shí),排列如下:

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

之后,你的輸出需要從左往右逐行讀取,產(chǎn)生出一個(gè)新的字符串,比如:“PAHNAPLSIIGYIR”。

請(qǐng)你實(shí)現(xiàn)這個(gè)將字符串進(jìn)行指定行數(shù)變換的函數(shù):

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

示例3

輸入:s = "A", numRows = 1
輸出:"A"

思路/解法

模擬法,根據(jù)所給條件,線性處理即可(Z字形存在一定規(guī)律,每當(dāng)固定的條件后前進(jìn)方向進(jìn)行轉(zhuǎn)變)。

class Solution {
public:
    string convert(string s, int numRows) {
        int rows = numRows;
	    int columns = ((s.length() / (2 * rows - 1)) + 1) * rows;//盡可能縮小所使用的空間,這里columns可優(yōu)化,并未精確求解
	    std::vector<std::vector<char>> arrs(rows, std::vector<char>(columns));

	    //初始化
	    for (int i = 0; i < rows; i++)
		    for (int j = 0; j < columns; j++)
			    arrs[i][j] = '0';

	    int x = 0, y = 0;
	    int index = 0;
	    while (index < s.length())
	    {
		    if (index < s.length() && x < rows)
			    arrs[x++][y] = s[index++];

		    if (index < s.length() && x == rows)
		    {
                 //更新x和y
			    y++;
			    x -= 2;
			    while (index < s.length() && x > 0)
				    arrs[x--][y++] = s[index++];
			    x = 0;//重置x
		    }
	    }

	    std::string res;
	    for (int i = 0; i < rows; i++)
	    {
		    for (int j = 0; j < columns; j++)
		    {
			    if (arrs[i][j] != '0' && arrs[i][j] != '\0')
				    res.push_back(arrs[i][j]);
		    }
	    }
	    return res;
    }
};

原文鏈接:https://blog.csdn.net/qq135595696/article/details/125687072

欄目分類
最近更新