# 6. ZigZag Conversion（Z字形输出数组）

### 官网

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

### 题目大意

• 1.之字型摆字符串然后横着输出重组了的字符串。

### 解题思路

• 1.字符串最后是这么摆的，每行都由主元素和插入元素组成，主元素中间插入一个元素，每层的主元素间隔为2*(n-1),插入的元素与它前面一个元素的间隔为2×(n-1)-2*i。

### AC代码

``````#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;

class Solution {
public:
string convert(string s, int numRows) {
if (s.empty()) {
return s;
}
int length = s.length();
if (length<=numRows||numRows==1) {
return s;
}
string sb = "";
//主元素之间的间隔
int step = 2*(numRows-1);
int count = 0;
for (int i = 0; i < numRows; ++i) {
//主元素之间插入元素与它前一个主元素的间隔
int interval = step - 2*i;
for (int j = i; j < length; j+=step) {
sb = sb + s[j];
//满足条件则插入
if (interval>0&&interval<step&&j+interval<length) {
sb = sb+s[j+interval];
}
}
}
return sb;
}
};

int main(int argc, char *argv[]) {
string aaa = "PAYPALISHIRING";
Solution solution;
aaa = solution.convert(aaa,3);
cout << aaa << endl;
}
``````
原文作者：Z字形编排问题
原文地址: https://blog.csdn.net/qq_16949707/article/details/52577765
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。