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"
.实现Z字形遍历字符串。基本思路:设定好步长来遍历字符串,按所要求的行数nRows来进行循环,把每次遍历到的字符保存在新建的字符串中,最后输出即可。实现代码:
class Solution {
public:
string convert(string s, int nRows) {
int length = s.size();
if (length <= nRows || nRows == 1)
return s;
char chars[length];
int step = 2*(nRows-1);
int count=0;
for(int i=0;i<nRows;i++)
{
int interval = step -2*i;
for(int j=i;j<length;j+=step)
{
chars[count] = s.at(j);
count++;
if(interval < step && interval > 0
&& j + interval < length)
{
chars[count] = s.at(j+interval);
count++;
}
}
}
string result=chars;
result=result.substr(0,length);
return result;
}
};
讨论:
在我之前编写的代码中,没有倒数第二句:result=result.substr(0,length);即取string中的前length个字符。这样结果会有错误,因为除了返回规定的字符串后,后面还带有一些乱码,比如要求返回ACB,则会返回ACB?###之类。我不知道产生这个结果的原因。欢迎大牛们指点!