[leetcode]ZigZag


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
字符串“PAYPALISHIRING”以Z字形图案写在给定数量的行上,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性)
然后逐行阅读:“PAHNAPLSIIGYIR”

编写将采用字符串的代码并在给定多行的情况下进行此转换

c++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
int length_s = s.length();
int num_z = (numRows * 2 - 2);//一个完整的z的字符个数
if (numRows == 1)
return s;
string ren;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j +i< length_s; j = j + num_z) {
ren =ren+ s[i + j];
if (i != 0 && i != numRows - 1&&num_z-i+j<length_s)
ren = ren+s[num_z - i + j];
}
}
return ren;
}
};
int main()
{
Solution s;
s.convert("PAYPALISHIRING",3);
}

算法

一个字符串以另外一种形式返回。找到返回字符串的规律

Z的规律:首先看原字符串的长度,再看每个Z需要多少个字符串;

在每一行中再循环每一个Z,循环每个Z的时候,要注意两个边界

第一个:是j循环的条件,每行的首个字母的索引是i+j,因此循环每个j的时候,要保证索引小于总长度

第二个:除了首末两行,其余的行每个Z都要返回两个字符串,找到这两个字符串的关系,即第二个字符串索引为Z字符个数-i+j,也要保证这个索引小于总长度

有了这两个边界保证,就不需要去考虑完整Z和不完整Z,完全利用索引去和长度的大小去判断字符串。