Title Description
The number of a given string according to the given row, to down, left to right from the Z-shaped arrangement. Example, the input string is the number of rows "LEETCODEISHIRING" is 3, arranged as follows:
LCIR
ETOESIIG
EDHN
After that, you need the output from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".
Thinking
- Violent solution to simulate the transformation process in order to get an answer, but time-consuming, large memory footprint
- Find the law, we find that the distance between the last line in the first two letters arranged to 2n-3, rather than the first law between the two letters is the last line: If the first character is defined as 0, the k-th character when the even-numbered, the next character pitch is 2 * (n- line-1), if k is odd, the next character is a distance 2 * line. This method only requires n times to traverse the string
Code
method one:
string convert(string s, int numRows) {
int len = s.length();
if (len<2 || numRows == 1)
return s;
string res;
int numCols = len / (numRows + numRows - 2)*(numRows - 1);
if (len % (numRows + numRows - 2) != 0)
{
if (len % (numRows + numRows - 2) <= numRows)
numCols++;
else
numCols += 1 + len % (numRows + numRows - 2) - numRows;
}
vector<vector<char>> Matrix(numRows, vector<char>(numCols));
int x = 0, y = 0;
for (int i = 0; i<len; i++)
{
Matrix[x][y] = s[i];
if (y % (numRows - 1) == 0)
{
if (x<numRows-1)
x++;
else
{
x--;
y++;
}
}
else
{
y++;
x--;
}
}
for (int i = 0; i<numRows; i++)
{
for (int j = 0; j<numCols; j++)
{
if (Matrix[i][j] != '\0')
res += Matrix[i][j];
}
}
return res;
}
Method Two:
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
if (len<2 || numRows == 1)
return s;
string res;
int line = 0;
while (line<numRows)
{
int index = line;
if (line == 0 || line == numRows - 1)
{
while (index<s.length())
{
res += s[index];
index = index + 2 * (numRows-1) ;
}
line++;
}
else
{
int count = 0;
while (index<s.length())
{
res += s[index];
if (count % 2 == 0)
index = index + 2 * (numRows - line-1);
else
index = index + 2 * line;
count++;
}
line++;
}
}
return res;
}
};