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 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”
其实写几组就能找到规律,转载别人的叙述
nRows = 2 0 2 4 6 ... 1 3 5 7
nRows = 3 0 4 8 ... 1 3 5 7 9 2 6 10
nRows = 4 0 6 12 ... 1 5 7 11 2 4 8 10 3 9
先计算一下每一个zig包含的字符个数,实际上是zigSize = nRows + nRows – 2
然后一行一行的加s中的特定元素就行。
第一行和最后一行都只需要加一个字符,每一个zig,而且在s中的index间隔是zigSize。
中间每一行需要添加两个字符到结果中去。第一个字符同上;第二个字符和前面添加这个字符在s上的inde相差正好是zigSize – 2*ir。ir是行index。
#include <iostream>
using namespace std;
class Solution {
public:
string convert(string s, int nRows)
{
if(nRows <= 1) return s; //特殊情况不能省
string ret;
int ssize = s.size();
int pace = nRows+nRows-2;
for(int i=0;i<nRows;i++)
{
for(int start=i;;start+=pace)
{
if(start>=ssize)//该处等于即可,或者ssize-1
break;
ret.append(1,s[start]);
if(i>0&&i<nRows-1)
{
int startmid = start+pace-2*i;
if(startmid<ssize)
ret.append(1,s[startmid]);
}
}
}
return ret;
}
};
int main()
{
string str = "PAYPALISHIRING";
Solution so;
cout<<so.convert(str,3);
return 0;
}
本文介绍了一种将字符串以ZigZag形式分布并重新读取的方法,通过实例展示了不同行数下字符串的分布模式,并提供了一段C++代码实现。

被折叠的 条评论
为什么被折叠?



