输入一个整数 n, 表示输出的行数,再输入一个字符串,输出 Z 字排列后的串。

比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

image

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。

输入:

3
COMPUTERVISION

输出:

CUVOOPTRIINMES


这题容易陷入创建一个二维数组,然后琢磨有多少列,其实不需要。

只需要 n 个字符串,然后依次,给第 0 个字符串添加字符、给第 1 个添加字符、给第 2 个添加字符...到行末则掉头,到第一行也掉头,直到把原始字符串中所有字符都添加完。最后把 n 个字符串拼接即可。

C++34 linesExpandCollapse
#include <bits/stdc++.h>
using namespace std;

int main() {
    int numRows;
    cin >> numRows;
    
    string s;
    cin >> s;
    
    // 边界情况直接返回
    if (numRows == 1 || numRows >= s.size()) {
        cout << s << endl;
        return 0;
    }
    
    vector<string> rows(numRows);
    int rowIndex = 0, direction = 1;
    
    for (char c : s) {
        if (rowIndex == 0) direction = 1;
        else if (rowIndex == numRows - 1) direction = -1;
        rows[rowIndex] += c;
        rowIndex += direction;
    }
    
    string ans;
    for (const string& row : rows) {
        ans += row;
    }
    cout << ans << endl;
    
    return 0;
}