From :https://leetcode.com/problems/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 RAnd 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"
.Solution 1:
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1) return s;
string result;
int off = 2*numRows-2, index, len=s.length(), po=0;
for(int i=0; i<numRows; i++) {
int index = i;
if(index==0 || index==numRows-1) {
while(index<len) {
result += s[index];
index += off;
}
} else {
int midOff = numRows-i-1, preIndex;
while(index<len) {
result += s[index];
preIndex = index;
index = 2*(index+midOff)-index;
if(index<len) {
result += s[index];
}
index = preIndex + off;
}
}
}
return result;
}
};
class Solution {
public:
string convert(string s, int rows) {
if(rows == 1) {
return s;
}
string ans;
int len = s.size(), step = rows + rows - 2;
for(int row=0; row<rows; ++row) {
if(0 == row || row+1 == rows) {
for(int i=row; i<len; i+=step) {
ans += s[i];
}
} else {
int off = rows - row - 1;
for(int i=row; i<len; i+=step) {
ans += s[i];
if(i+off+off < len) {
ans += s[i+off+off];
}
}
}
}
return ans;
}
};
solution 2:
class Solution {
public:
string convert(string s, int nRows) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (nRows <= 1 || s.length() == 0)
return s;
string res = "";
int len = s.length();
for (int i = 0; i < len && i < nRows; ++i)
{
int indx = i;
res += s[indx];
for (int k = 1; indx < len; ++k)
{
//第一行或最后一行,使用公式1:
if (i == 0 || i == nRows - 1)
{
indx += 2 * nRows - 2;
}
//中间行,判断奇偶,使用公式2或3
else
{
if (k & 0x1) //奇数位
indx += 2 * (nRows - 1 - i);
else indx += 2 * i;
}
//判断indx合法性
if (indx < len)
{
res += s[indx];
}
}
}
return res;
}
};