# [LeetCode] 6. ZigZag Conversion 之字型转换字符串

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"


Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

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

0 2 4 6 8 A C E

1 3 5 7 9 B D F

0   4    8     C

1 3 5 7 9 B D F

2    6   A     E

0     6        C

1   5 7   B  D

2 4   8 A    E

3      9       F

class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 1) return s;
string res;
int size = 2 * numRows - 2, n = s.size();
for (int i = 0; i < numRows; ++i) {
for (int j = i; j < n; j += size) {
res += s[j];
int pos = j + size - 2 * i;
if (i != 0 && i != numRows - 1 && pos < n) res += s[pos];
}
}
return res;
}
};

class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 1) return s;
string res;
int i = 0, n = s.size();
vector<string> vec(numRows);
while (i < n) {
for (int pos = 0; pos < numRows && i < n; ++pos) {
vec[pos] += s[i++];
}
for (int pos = numRows - 2; pos >= 1 && i < n; --pos) {
vec[pos] += s[i++];
}
}
for (auto &a : vec) res += a;
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/6

Zigzag Iterator

Binary Tree Zigzag Level Order Traversal

https://www.cnblogs.com/springfor/p/3889414.html

https://leetcode.com/problems/zigzag-conversion/discuss/3403/Easy-to-understand-Java-solution

https://leetcode.com/problems/zigzag-conversion/discuss/3417/A-10-lines-one-pass-o(n)-time-o(1)-space-accepted-solution-with-detailed-explantation

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2014-11-28 13:03  Grandyang  阅读(24438)  评论(7编辑  收藏  举报