LeetCode6 ZigZag Conversion

时间:2024-01-19 13:34:32

题意:

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".   (Easy)

分析:

首先是理解题意,题目例子举得不好...起始ZigZag的意思以4举例更易懂一些。

1           7             13

2      6   8        12

3   5      9   11

4          10

读懂了题意,其实就是判断好什么时候向下,什么时候向上即可,我用的vector<string>实现,维护nRows个string,最后拼接在一起。

代码:

 class Solution {
public:
string convert(string s, int numRows) {
if (numRows == ) {
return s;
}
vector<string> v(numRows);
int j = ;
for (int i = ; i < s.size(); ++i) {
if ( (i / (numRows - ) ) % == ) {
v[j].insert(v[j].end(), s[i]);
j ++;
}
if ( (i / (numRows - )) % == ) {
v[j].insert(v[j].end(), s[i]);
j--;
}
}
string result;
for (int i = ; i < v.size(); ++i) {
result += v[i];
}
return result;
}
};