题目描述
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".
Solution:
纯粹的模拟之字形路线,时间复杂度为O(n)
题目大意:
给一个字符串,按照之字形排列成一个矩阵,然后将矩阵每一行连起来构成一个字符串,求这个字符串,题意不清,还是要给一个图才能明白
可以将之字形路线压缩,例如上例中压缩之后的到如下表所示
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 | |
实现代码:
class Solution {
public:
string convert(string s, int nRows) {
if(nRows==1)return s;
string chs=string(s); //初始化chs为s;
int index=0;
if(nRows==2)
{
for(int i=0;i<s.size();i+=2)chs[index++]=s[i];
for(int i=1;i<s.size();i+=2)chs[index++]=s[i];
return chs;
}
char map[1000][1000];
for(int i=0;i<nRows;i++)
{
for(int j=0;j<s.size();j++)
map[i][j]=0;
}
index=0;
int col=0;
while(s[index])
{
if(col%2)
{
int i=nRows-2;
while(i>=1 && s[index])map[i--][col]=s[index++];
}
else
{
int i=0;
while(i<nRows && s[index])map[i++][col]=s[index++];
}
col++; //将所有的字符全部赋给map之后,col会再自加1;
}
index=0;
for(int i=0;i<nRows;i++)
{
for(int j=0;j<col;j++) //因此这里用col;
{
if(map[i][j])chs[index++]=map[i][j];
}
}
return chs;
}
};
public:
string convert(string s, int nRows) {
if(nRows==1)return s;
string chs=string(s); //初始化chs为s;
int index=0;
if(nRows==2)
{
for(int i=0;i<s.size();i+=2)chs[index++]=s[i];
for(int i=1;i<s.size();i+=2)chs[index++]=s[i];
return chs;
}
char map[1000][1000];
for(int i=0;i<nRows;i++)
{
for(int j=0;j<s.size();j++)
map[i][j]=0;
}
index=0;
int col=0;
while(s[index])
{
if(col%2)
{
int i=nRows-2;
while(i>=1 && s[index])map[i--][col]=s[index++];
}
else
{
int i=0;
while(i<nRows && s[index])map[i++][col]=s[index++];
}
col++; //将所有的字符全部赋给map之后,col会再自加1;
}
index=0;
for(int i=0;i<nRows;i++)
{
for(int j=0;j<col;j++) //因此这里用col;
{
if(map[i][j])chs[index++]=map[i][j];
}
}
return chs;
}
};