题目:
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”.
class Solution {
public:
string convert(string s, int nRows) {
if (nRows <= 1) return s;
string str="";
int len=s.length();
for(int i=0; i<len && i<nRows; i++) {
int idx = i;
str += s[idx];
//看对每一行是否有可以加入到str上的元素
for(int k=1; idx < len; k++) {
//如果是 第0行 或者是 最后一行 的判断方法
if(i == 0 || i == nRows-1) {
idx += 2*nRows - 2;
//如果是 中间行 的判断方法
// 即后面的元素所在列+1如果是奇数,则下个元素位置则为该位置+2*(nRows-1-i);
// 如果是偶数,则下个元素位置为该位置+2*i。
}else {
if(k%2!=0)
{
//也可以写成k&0x=1,表示8位数取最右边一位数。
/*其效果为取k的二进制中最右边的数字,
该式也可以用做判断k的奇偶性
如果k为奇数,其计算结果为1,否则为0。*/
idx += 2*(nRows-1-i);
}else {
idx += 2*i;
}
}
//看原串中是否存在该元素,存在就加入
if(idx < len) {
str += s[idx];
}
}
}
return str;
}
};