ZigZag Conversion
Total Accepted: 5160 Total Submissions: 22837My Submissions
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"
.
Have you been asked this question in an interview?
I treat this problem in a direct way:
class Solution {
public:
string convert(string s, int nRows) {
int i, j, flg;
vector<char> vec;
vector<vector<char>> zigzag(nRows,vec);
for (i = 0, j = 0, flg = 1; i < s.length(); ++i) {
zigzag[j].push_back(s[i]);
if (flg && j == nRows - 1)
flg = 0;
else if (!flg && j == 0)
flg = 1;
if (nRows > 1)
j = flg > 0 ? (j + 1):(j - 1);
}
string res = "";
for (i = 0; i < nRows; ++i)
for (j = 0; j < zigzag[i].size(); ++j)
res += zigzag[i][j];
return res;
}
};
But a better way is from http://blog.unieagle.net/2012/11/08/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Azigzag-conversion/
class Solution {
public:
string convert(string s, int nRows) {
int len = s.length(), zigSize = nRows*2 - 2, i, j, tmp;
string res = "";
if (nRows <= 1) return s;
for (i = 0; i < nRows; ++i) {
for (j = i; j < len; j += zigSize) {
res += s.substr(j,1);
tmp = j + zigSize - 2 * i;
if (i != 0 && i != nRows - 1 && tmp < len) {
res += s.substr(tmp, 1);
}
}
}
return res;
}
};
Python Version:
class Solution:
def convert(self, s, numRows):
slen = len(s)
if (numRows <= 1):
return s
res = ""
zigSize = numRows * 2-2
for i in range(numRows):
for j in range(i, slen, zigSize):
res += s[j]
tmp = j - 2 * i + zigSize
if (i > 0 and i < numRows-1 and tmp < slen):
res += s[tmp]
return res